how to cache reflection in C#

廉价感情. 提交于 2019-12-13 05:41:39

问题


Hello there I am familiar with reflection quite a bit, I have been through loads of examples and I know how it works and for what purpose we can use it. But I didn't get any examples of caching the reflection, neither do I know what does it mean. And somehow I have to use caching of reflection in of the projects that I am doing.

Therefore, I would be obliged if some one can briefly explain this concept as well as give some examples of it, a link to existing examples would also be appreciated. And please also describe the reflection of attributes as well as its caching. Thanks in advance.

Regards Umair


回答1:


You would cache it like you would anything else:

 var cache = new Dictionary<Type, IEnumerable<Attribute>>();

 // obj is some object
 var type = obj.GetType();
 var attributes = type.GetCustomAttributes(typeof(MyAttribute), true);
 cache.Add(type, attributes);



回答2:


I suggest not caching the reflection (hehe) because it is (of course) done by the runtime. If you mean to reduce lookup time and perhaps dynamic invocation overhead

  1. Just hold a reference to the MethodInfo/PropertyInfo object to call
  2. transform the reflected methods into Expressions. I suggest using DLINQ in order not to reinvent the wheel. See here for more pointers Parsing a string C# LINQ expression

And whatever you do: don't complicate things by optimizing prematurely.



来源:https://stackoverflow.com/questions/5669272/how-to-cache-reflection-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!