What's the difference between [Something] and

2019-02-22 14:12发布

问题:

This question already has an answer here:

  • Why can I use the shorthand `[Authorize]` instead of the name of the actual class, `[AuthorizeAttribute]`? [duplicate] 4 answers

This has probably been already asked but it's hard to search for.

What is the difference between [Something] and [SomethingAttribute]?

Both of the following compile:

[DefaultValue(false)]
public bool Something { get; set; }
[DefaultValueAttribute(false)]
public bool SomethingElse { get; set; }

Are there any differences between these apart from their appearance? What's the general guideline on their use?

回答1:

There is no functional difference. [Something] is just shorthand syntax for [SomethingAttribute].

From MSDN:

By convention, all attribute names end with Attribute. However, several languages that target the runtime, such as Visual Basic and C#, do not require you to specify the full name of an attribute. For example, if you want to initialize System.ObsoleteAttribute, you only need to reference it as Obsolete.



回答2:

In most cases they are the same. As already said you can typically use them interchangeable except when you have both DefaultValue and DefaultValueAttribute defined. You can use both of these without ambiguity errors by using the verbatim identifier (@).

The C#LS section 17.2 makes this more clear:

[AttributeUsage(AttributeTargets.All)]
public class X: Attribute {}

[AttributeUsage(AttributeTargets.All)]
public class XAttribute: Attribute {}

[X] // Error: ambiguity
class Class1 {}

[XAttribute] // Refers to XAttribute
class Class2 {}

[@X] // Refers to X
class Class3 {}

[@XAttribute] // Refers to XAttribute
class Class4 {}

This refers to the actual usage of the attribute. Of course if you require use of the type name such as when using typeof or reflection, you'll need to use the actual name you gave the type.



回答3:

Both are same in the context where attribute declaration goes. Former is shorter form of latter. But it does makes the difference inside a method.

For example if you say typeof(DefaultValue) in some method, that won't compile. You'll have to say typeof(DefaultValueAttribute) instead.

private void DoSomething()
{
    var type = typeof(DefaultValue);//Won't compile
    var type2 = typeof(DefaultValueAttribute);//Does compile
}