C# custom attribute naming
I have a custom Attribute class that I defined as:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class MyCustomAttribute : System.Attribute
{
...
}
From the microsoft website:
By convention, the name of the attribute class ends with the word Attribute. While not required, this convention is recommended for readability. When the attribute is applied, the inclusion of the word Attribute is optional.
So, the attribute can be use by either
[MyCustom()]
or
开发者_Go百科[MyCustomAttribute()]
My question to you all, is if anyone has experienced any problems with using the abbreviated version of the name vs the full name? I am running 4.0 framework.
Thanks!
No problems.
Underneath in compiled IL the name always has Attribute appended to it (the full type name).
Based on ECMA-334 (C# spec) 24.2, the resolution is done first by exact match, then by appending "Attribute" to the name given in []. Additionally, if there is a conflict (ex: MyAttribute, and MyAttributeAttribute) a compile time error is generated when "MyAttribute" would be used.
It should be fine... I'd just advise you not to introduce two attributes with names only differing by the number of Attribute suffixes:
public class FooAttribute : Attribute { }
public class FooAttributeAttribute : Attribute { }
[FooAttribute] // Could be either!
I suspect the exact match would win here, but please don't introduce the ambiguity in the first place. (I haven't checked the spec.)
Nope. Easy as pie!
Also, you can use it without the empty ()
parentheses
In general, you shouldn't hit any problems. The C# compiler is smart enough to resolve it to the proper type in either case.
精彩评论