Two questions about attributes:
The idea is that I want to make a list of all the classes in my assembly that have my attribute applied to it. I could of course iterate through all of them with reflection and check - but it would be nicer if the attribute could simply append to a global static list upon instantiation.
Which of the following are correct ways to specify the targets for a custom attribute? A. By applying AttributeUsage to the custom attribute's class definition.
The following code fragment specifies that a custom attribute can be applied to any class or method: C# Copy. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] End Class.
In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.
Attributes are not automatically instantiated upon application startup. The only way to see which types (or any IL element, for that matter) has the attribute applied is to iterate everything and check one by one. Consequently, attributes can't automatically take control of a program.
They are basically metadata attached to some stuff. Their constructor is called when reflection instantiates the attribute class that represents the attribute at run time. This happens only when you request reflection to do so (by Type.GetCustomAttributes
method.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With