问题
Something which implements the ICustomAttributeProvider
interface will allow you to get custom attributes that have been applied to it via the GetCustomAttributes
method. As I understand it, a custom attribute is basically a special class (ending in "Attribute" and extending the Attribute
class) that is created to be applied to something like a method or class using the appropriate syntax ([FooAttribute]
just before the method/class/etc. in C#, for example). But if that is a custom attribute, what is a non-custom attribute? I used to think that attributes that were bundled with .NET were non-custom, but GetCustomAttributes
even returns me attributes like System.ThreadStaticAttribute
, which are very core to the .NET framework.
Is there such a thing as a non-custom attribute, or is "custom attribute" just a tautology?
回答1:
I don't know if the following has any relevance, but if you say
var a = typeof(string).Attributes;
you get a value of a flags enum type called TypeAttributes. Maybe these flags are the "non-custom" attributes of the type?
回答2:
Everything that derives from Attribute
is a custom attribute.
"Attribute" is a generic term. Objects in the real world have innumerable attributes. Classes, members and parameters all have attributes that we can describe -- names, types, accessors, number of members, inheritance information, etc.
Custom attributes are things that we tack on -- aspects that we want to associate and use to describe, but which are not intrinsic.
回答3:
See Wikipedia, quoting:
Developers can add metadata to their code through attributes. There are two types of attributes, custom and pseudo custom attributes, and to the developer these have the same syntax. Attributes in code are messages to the compiler to generate metadata. In CIL, metadata such as inheritance modifiers, scope modifiers, and almost anything that isn't either opcodes or streams, are also referred to as attributes.
See also the CLI specification about extending metadata, where references are found to the term "custom" attributes (e.g. I.9.7 in http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf)
来源:https://stackoverflow.com/questions/13387551/custom-vs-non-custom-attributes