When is it run? Does it run for each object to which I apply it, or just once? Can it do anything, or its actions are restricted?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
When is the constructor run? Try it out with a sample:
And what is the output?
So, the attribute constructor is run when we start to examine the attribute. Note that the attribute is fetched from the type, not the instance of the type.
The constructor is run every time the
GetCustomAttributes
is invoked, or whenever some other code invokes the constructor directly (not that there's a good reason to do so, but it's not impossible either).Note that at least in .NET 4.0, the attribute instances are not cached; a fresh instance is constructed every time
GetCustomAttributes
is called:It is not the best idea to have attributes behave like this, of course. At the very least, note that
GetCustomAttributes
is not documented to behave like this; in fact, what happens in the above program is not specified in the documentation.The metadata in the executable or DLL stores:
When I get to that section of my CLI implementation, I plan to lazy-call the constructor the first time
GetCustomAttributes()
is called for theICustomAttributeProvider
. If a particular attribute type is requested, I'll only construct the ones required to return that type.Set a debugger break-point inside an attribute constructor and write some reflection code that reads those attributes. You'll notice that the attribute objects won't be created until they are returned from the relfection API. Attributes are per class. They are part of the meta data.
Have a look at this:
Program.cs
MyAttribute.cs
Result
But don't worry about the performance of attribute constructors. They are the fastest part of reflection :-P