问题
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
- Just hold a reference to the MethodInfo/PropertyInfo object to call
- 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