简体   繁体   中英

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

[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM