0

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

Omayr
  • 1,949
  • 4
  • 22
  • 35
  • 2
    You don't know What it is, you don't know Why but still you _have to_ cache something? – H H Apr 14 '11 at 20:37
  • this Thread will help you : http://stackoverflow.com/questions/1204748/cache-reflection-results-class-properties – Farzin Zaker Apr 14 '11 at 20:48
  • See also: http://stackoverflow.com/q/5668569/23354 – Marc Gravell Apr 14 '11 at 20:49
  • 1
    @henk Holterman: There is a tip for you Sir, if you are knowledgeable please share your knowledge don't degrade people. You completely misunderstood the question, I never said that I don't know reflection. The point was caching the reflection, and I don't want to bother people unnecessarily, I googled it but couldn't find something useful. – Omayr Apr 15 '11 at 14:30
  • 2
    I didn't intend to degrade you but I was (and am) critical of the question. The lack of detail (how is the metadat used?) makes it hard/impossible to answer. See below, just 2 attempts based on a lot of guesswork. – H H Apr 15 '11 at 15:11

2 Answers2

7

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);
satnhak
  • 9,407
  • 5
  • 63
  • 81
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.

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 4
    Reflection is not cached excessively. If you do a lot of meta-programming (in particular, common in library development), effective caching of reflection can make all the difference. Oh, and `Expression` is not any more optimized than `MethodInfo` - it is only when you compile it to a *strongly typed delegate* that it becomes useful. – Marc Gravell Apr 14 '11 at 20:51