调用 C# 类声明之前的方括号中的内容是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9472168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:32:51  来源:igfitidea点击:

What is the thing in square brackets that comes before a C# class declaration called?

c#

提问by Bit Hunter

What is the [something]in

什么是[something]

[something]
public class c1 {

}

called in C#? What does it do?

在 C# 中调用?它有什么作用?

回答by Teoman Soygul

That's an Attribute.

那是一个Attribute

回答by JaredPar

This is known as an attribute application / usage. It associates an instance of a given Attributewith a type. These are user definitable items. For example

这称为属性应用程序/用法。它将给定的实例Attribute与类型相关联。这些是用户可定义的项目。例如

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

This is an attribute which can be applied on ever place an attribute is legal

这是一个属性,可以应用于任何属性合法的地方

// Assembly level
[assembly: Example]

// Class
[Example]
public class C1 {
  // Field
  [Example]
  public int m_field;

  // Method
  [Example]
  public void Test() { }
}

More locations are possible but hopefully this gets the general idea across. You may also want to check out this tutorial

更多的位置是可能的,但希望这能传达总体思路。您可能还想查看本教程

回答by Sam Axe

Its called an Attribute. A class that ends in "Attribute", and inherits from Attribute:

它被称为一个属性。以“Attribute”结尾的类,并继承自 Attribute:

public class SomethingAttribute : Attribute {

}

If you are creating one, be sure to look up the AttributeUsageAttributeclass.

如果您正在创建一个,请务必查找AttributeUsageAttribute类。

回答by Dmitry Savy

C# Attributes. Please see this documentation.

C# 属性。请参阅此文档。