利用lambda表达式树优化反射详解

2020-01-05 10:10:10丽君

在将代码应用到实例:


   Dog dog = new Dog();
   PropertyInfo propertyInfo = dog.GetType().GetProperty(nameof(dog.Name));
   
   //反射操作
   propertyInfo.SetValue(dog, "WLJ");
   String result = propertyInfo.GetValue(dog) as String;
   Console.WriteLine(result);
   
   //表达式树的操作
   Property property = new Property(propertyInfo);
   property.SetValue(dog, "WLJ2");
   String result2 = propertyInfo.GetValue(dog) as String;
   Console.WriteLine(result2);

发现其实现的目的与反射一致,但效率却有明显的提高。

以下测试以下他们两之间的效率。测试代码如下:


   Student student = new Student();
   PropertyInfo propertyInfo = student.GetType().GetProperty(nameof(student.Name));
   Property ExpProperty = new Property(propertyInfo);

   Int32 loopCount = 1000000;
   CodeTimer.Initialize(); //测试环境初始化

   //下面该方法个执行1000000次

   CodeTimer.Time("基础反射", loopCount, () => { 
    propertyInfo.SetValue(student, "Fode",null);
   });
   CodeTimer.Time("lambda表达式树", loopCount, () => {
    ExpProperty.SetValue(student, "Fode");
   });
   CodeTimer.Time("直接赋值", loopCount, () => {
    student.Name = "Fode";
   });
   Console.ReadKey();

其.Net4.0环境下运行结果如下:

lambda,表达式树,反射

.Net Core环境下运行结果:

lambda,表达式树,反射