Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 什么';[某物]和[某物属性]之间的区别是什么_C#_.net Attributes - Fatal编程技术网

C# 什么';[某物]和[某物属性]之间的区别是什么

C# 什么';[某物]和[某物属性]之间的区别是什么,c#,.net-attributes,C#,.net Attributes,这可能已经被问过了,但很难找到 [Something]和[SomethingAttribute]之间有什么区别 以下两项都需要编译: [DefaultValue(false)] 公共bool Something{get;set;} [DefaultValueAttribute(false)] 公共bool SomethingElse{get;set;} 除了它们的外观,它们之间有什么区别吗?使用它们的一般指导原则是什么?没有功能上的区别[Something]只是[SomethingAttri

这可能已经被问过了,但很难找到

[Something]
[SomethingAttribute]
之间有什么区别

以下两项都需要编译:

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

除了它们的外观,它们之间有什么区别吗?使用它们的一般指导原则是什么?

没有功能上的区别
[Something]
只是
[SomethingAttribute]
的简写语法

发件人:

按照惯例,所有属性名称都以attribute结尾。然而, 以运行时为目标的几种语言,如Visual Basic和 C#,不要求您指定属性的全名。对于 例如,如果要初始化System.ObsoleteAttribute,则只需 需要将其引用为已过时


两者在属性声明所在的上下文中是相同的。前者是后者的简称。但它确实在方法内部产生了差异

例如,如果在某个方法中说
typeof(DefaultValue)
,则不会编译。您必须改为说
typeof(DefaultValueAttribute)

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

大多数情况下,它们是相同的。如前所述,除非同时定义了
DefaultValue
DefaultValueAttribute
,否则通常可以互换使用它们。通过使用逐字标识符(
@
),您可以使用这两种方法而不会出现歧义错误

C#LS第17.2节更清楚地说明了这一点:

[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 {}

这是指该属性的实际使用情况。当然,如果您需要使用类型名称,例如在使用
typeof
或reflection时,您需要使用您提供的类型的实际名称。

没有区别;首选
[DefaultValue(false)]
。更好的问题是“xxxAttribute”为什么存在:-)。我想这对
DefaultValue
DefaultValueAttributeAttribute
类型很重要。如果向下投票人能够指出答案的错误,那就更好了。没有问题。我认为,选民不知道你在说什么,因为这显然是一个很好的答案。在声明性属性上下文之外,不能只从末尾删除“attribute”。