简体   繁体   中英

how to cache reflection in C#

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

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM