缓存反射属性获取器/设置器的最佳方法? [英] Best way to cache a reflection property getter / setter?

查看:69
本文介绍了缓存反射属性获取器/设置器的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that Reflection can be expensive. I have a class that gets/sets to properties often, and one way I figured was to cache the reflection somehow. I'm not sure if I'm supposed to cache an expression or what to do here really. This is what I'm currently doing:

typeof(T).GetProperty(propName).SetValue(obj, value, null);
typeof(T).GetProperty(propName).GetValue(obj, null);

那么...什么是使此过程更快的最佳方法?

So... what would be the best way to make this quicker?

推荐答案

您应该缓存

typeof(T).GetProperty(propName); 

typeof(T).GetProperty(propName);

另一种可能的方法是将 PropertyInfo.GetGetMethod方法(或用于设置程序的PropertyInfo.GetSetMethod方法),其中 Delegate.CreateDelegate方法,并在每次需要获取/设置值时调用生成的委托。如果您需要将其与泛型一起使用,则可以使用以下问题中的方法:具有未知类型的CreateDelegate

Another possible approach is to combine PropertyInfo.GetGetMethod Method (or PropertyInfo.GetSetMethod Method for setter) with Delegate.CreateDelegate Method and invoke the resulting delegate every time you need to get/set values. If you need this to work with generics you can use approach from this question: CreateDelegate with unknown types

与反射相比,它应该快得多:
进行反思飞行并探索代表

This should be much faster compared to reflection: Making reflection fly and exploring delegates

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

There are also other ways to get/set values in a faster way. You can use expression trees or DynamicMethod to generate the il at runtime. Have a look at these links:

使用DynamicMethod的最新调用

Delegate.CreateDelegate与DynamicMethod与Expression

这篇关于缓存反射属性获取器/设置器的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆