缓存反射属性getter/setter的最佳方法是什么?

mic*_*ael 13 c# reflection performance caching properties

我知道反思可能很昂贵.我有一个经常获取/设置属性的类,我想到的一种方法是以某种方式缓存反射.我不确定我是否应该缓存表达式或者在这里做什么.这就是我目前正在做的事情:

typeof(T).GetProperty(propName).SetValue(obj, value, null);
typeof(T).GetProperty(propName).GetValue(obj, null);
Run Code Online (Sandbox Code Playgroud)

那么......什么才能让这个更快?

Gio*_*rgi 11

你应该缓存结果

typeof(T).GetProperty(propName); 
Run Code Online (Sandbox Code Playgroud)

typeof(T).GetProperty(propName);
Run Code Online (Sandbox Code Playgroud)

另一种可能的方法是将PropertyInfo.GetGetMethod方法(或用于setter的PropertyInfo.GetSetMethod方法)与Delegate.CreateDelegate方法结合使用,并在每次需要获取/设置值时调用生成的委托.如果您需要使用泛型来处理泛型,可以使用此问题的方法:CreateDelegate包含未知类型

与反射相比,这应该快得多: 使反射飞行并探索代表

还有其他方法可以更快地获取/设置值.您可以使用表达式树或DynamicMethod在运行时生成il.看看这些链接:

使用DynamicMethod进行后期绑定调用

Delegate.CreateDelegate与DynamicMethod vs Expression

  • 你说"你应该缓存X和Y的结果",但X和Y是一回事吗? (5认同)