public class Order
{
public string OrderId { get; set; }
}
public class SetterWrapper<TTarget, TValue>
{
private Action<TTarget, TValue> _setter;
public SetterWrapper(PropertyInfo propInfo)
{
if (propInfo == null)
throw new ArgumentNullException("propertyInfo");
if (!propInfo.CanWrite)
throw new NotSupportedException("属性是只读或Private Setter");
MethodInfo setMethod = propInfo.GetSetMethod(true);
_setter = (Action<TTarget, TValue>)Delegate.CreateDelegate(typeof(Action<TTarget, TValue>), null, setMethod);
}
public void SetValue(TTarget target, TValue val)
{
if (_setter != null)
{
_setter(target, val);
}
}
}
public class GetterWrapper<TTarget, TValue>
{
private Func<TTarget, TValue> _getter;
public GetterWrapper(PropertyInfo propInfo)
{
if (propInfo == null)
throw new ArgumentNullException("propertyInfo");
if (!propInfo.CanRead)
throw new NotSupportedException("属性是不可读或Private Getter");
MethodInfo getMethod = propInfo.GetGetMethod();
_getter = (Func<TTarget, TValue>)Delegate.CreateDelegate(typeof(Func<TTarget, TValue>), null, getMethod);
}
public TValue GetValue(TTarget target)
{
if (_getter != null)
{
return _getter(target);
}
return default(TValue);
}
}
static void Main(string[] args)
{
Order order=new Order(){OrderId = "W1234566"};
PropertyInfo piInfo = typeof(Order).GetProperty("OrderId");
int maxCount = 1000*1000;
string v = string.Empty;
Stopwatch sw = new Stopwatch();
sw.Reset();
sw.Start();
for (int i = 0; i < maxCount; i++)
{
order.OrderId = i.ToString();
v = order.OrderId;
}
sw.Stop();
Console.WriteLine("直接访问:{0}", sw.ElapsedTicks);
sw.Reset();
sw.Start();
for (int i = 0; i < maxCount; i++)
{
piInfo.SetValue(order,i.ToString());
v = piInfo.GetValue(order).ToString();
}
sw.Stop();
Console.WriteLine("直接反射:{0}", sw.ElapsedTicks);
sw.Reset();
sw.Start();
GetterWrapper<Order, string> getter = new GetterWrapper<Order, string>(piInfo);
SetterWrapper<Order, string> setter = new SetterWrapper<Order, string>(piInfo);
for (int i = 0; i < maxCount; i++)
{
setter.SetValue(order, i.ToString());
v = getter.GetValue(order);
}
sw.Stop();
Console.WriteLine("泛型妥托反射:{0}", sw.ElapsedTicks);
Console.Read();
}
//win7,vs 2013,8G内存,i5Cpu下测试