简体   繁体   English

“属性”在此属性上是什么意思?

[英]What does “property” mean on this attribute?

[property: Obsolete]
static int X
{
    get { return 42; }
}

In the code above, what purpose does the word "property" serve? 在上面的代码中,“财产”一词的目的是什么? The code seems to work the same way if I replace [property: Obsolete] with [Obsolete]. 如果我将[属性:已过时]替换为[已过时],则代码似乎以相同的方式工作。 And although "property" is coloured blue in Visual Studio, it does not appear in the list of C# keywords: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ 而且,尽管“属性”在Visual Studio中显示为蓝色,但它并未出现在C#关键字列表中: https : //docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/

The Attribute specification defines this as an attribute target . 属性规范将其定义为attribute target

Certain contexts permit the specification of an attribute on more than one target. 某些上下文允许在多个目标上指定属性。 A program can explicitly specify the target by including an attribute_target_specifier. 程序可以通过包含attribute_target_specifier来显式指定目标。 When an attribute is placed at the global level, a global_attribute_target_specifier is required. 将属性放在全局级别时,需要global_attribute_target_specifier。 In all other locations, a reasonable default is applied, but an attribute_target_specifier can be used to affirm or override the default in certain ambiguous cases (or to just affirm the default in non-ambiguous cases). 在所有其他位置,将应用合理的默认值,但是在某些模棱两可的情况下,可以使用attribute_target_specifier确认或覆盖默认值(或者在非模棱两可的情况下,只需确认默认值)。

It also states that in many cases, like the one you mention, it is permitted but not necessary. 它还指出,在许多情况下(如您提到的情况),这是允许的,但不是必需的。

In other contexts, inclusion of an attribute_target_specifier is permitted but unnecessary. 在其他情况下,允许包含attribute_target_specifier,但不是必需的。 For instance, a class declaration may either include or omit the specifier type. 例如,类声明可以包含或省略说明符类型。

This is an attribute target specification . 这是属性目标规范

In your code the use of it is not really necessary, since there is just one allowed target for that attribute at that place. 在您的代码中,实际上并不需要使用它,因为在该位置该属性只有一个允许的目标。 The Obsolete attribute can be placed on a type, method or a property, but if placed on a property, only the property target specifier is allowed (and used implicitly). 可以将Obsolete属性放置在类型,方法或属性上,但是如果放置在属性上,则仅允许使用property目标说明符(并隐式使用)。

The most practical use for this is the assembly target specifier, where you can set assembly configuration through attributes: 最实际的用途是assembly目标说明符,您可以在其中通过属性设置组装配置:

[assembly: AssemblyProduct("Foo bar")]

You can set the allowed targets on your custom attributes using AttributeUsage . 您可以使用AttributeUsage在自定义属性上设置允许的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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