What's the difference between [Something] and [SomethingAttribute] [duplicate]

≡放荡痞女 提交于 2019-12-01 20:12:48

问题


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
}


来源:https://stackoverflow.com/questions/28440691/whats-the-difference-between-something-and-somethingattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!