/// <summary> /// 快速调用PropertyInfo的GetValue方法 /// </summary> /// <param name="propertyInfo"></param> /// <param name="obj"></param> /// <returns></returns> public static object FastGetValue(this PropertyInfo propertyInfo, object obj) { if (propertyInfo == null) { throw new ArgumentNullException("propertyInfo"); } return(GetterSetterFactory.GetPropertyGetterWrapper(propertyInfo).Get(obj)); }
/// <summary> /// 快速调用PropertyInfo的SetValue方法 /// </summary> /// <param name="propertyInfo"></param> /// <param name="obj"></param> /// <param name="value"></param> public static void FastSetValue(this PropertyInfo propertyInfo, object obj, object value) { if (propertyInfo == null) { throw new ArgumentNullException("propertyInfo"); } GetterSetterFactory.GetPropertySetterWrapper(propertyInfo).Set(obj, value); }
public static void Test() { Console.WriteLine(System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion()); int count = 1000000; OrderInfo testObj = new OrderInfo(); PropertyInfo propInfo = typeof(OrderInfo).GetProperty("OrderID"); Console.Write("直接访问花费时间: "); Stopwatch watch1 = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { testObj.OrderID = 123; } watch1.Stop(); Console.WriteLine(watch1.Elapsed.ToString()); SetValueDelegate setter2 = DynamicMethodFactory.CreatePropertySetter(propInfo); Console.Write("EmitSet花费时间: "); Stopwatch watch2 = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { setter2(testObj, 123); } watch2.Stop(); Console.WriteLine(watch2.Elapsed.ToString()); Console.Write("纯反射花费时间: "); Stopwatch watch3 = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { propInfo.SetValue(testObj, 123, null); } watch3.Stop(); Console.WriteLine(watch3.Elapsed.ToString()); Console.WriteLine("----------------------------------"); Console.WriteLine("{0} / {1} = {2}", watch3.Elapsed.ToString(), watch1.Elapsed.ToString(), watch3.Elapsed.TotalMilliseconds / watch1.Elapsed.TotalMilliseconds); Console.WriteLine("{0} / {1} = {2}", watch3.Elapsed.ToString(), watch2.Elapsed.ToString(), watch3.Elapsed.TotalMilliseconds / watch2.Elapsed.TotalMilliseconds); Console.WriteLine("{0} / {1} = {2}", watch2.Elapsed.ToString(), watch1.Elapsed.ToString(), watch2.Elapsed.TotalMilliseconds / watch1.Elapsed.TotalMilliseconds); Console.Write("泛型委托花费时间: "); SetterWrapper <OrderInfo, int> setter3 = new SetterWrapper <OrderInfo, int>(propInfo); Stopwatch watch4 = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { setter3.SetValue(testObj, 123); } watch4.Stop(); Console.WriteLine(watch4.Elapsed.ToString()); Console.Write("通用接口花费时间: "); ISetValue setter4 = GetterSetterFactory.CreatePropertySetterWrapper(propInfo); Stopwatch watch5 = Stopwatch.StartNew(); watch5.Start(); for (int i = 0; i < count; i++) { setter4.Set(testObj, 123); } watch5.Stop(); Console.WriteLine(watch5.Elapsed.ToString()); }