问题描述
我已经看到了很多的使用 []
,例如 [STAThread]
,然后C#程序在code如下。另一个典型的例子是函数[DllImport]
。
I have seen a lot of C# programs that use the []
, for example [STAThread]
and then the code follows. Another classic example is [DLLImport]
.
我知道什么是 STAThread
意思,但我的问题是什么是方括号的意义,基本上是什么,他们告诉编译器?
I know what STAThread
means but my question is what is the significance of the square brackets, essentially what do they tell the compiler?
推荐答案
这是一个属性。属性是元数据的一种形式,可以附加各种code要素:类,方法,组件等
It's an attribute. Attributes are a form of metadata that you can attach to various code elements: classes, methods, assemblies etc.
一些属性有特殊含义的C#编译器,比如 [Serializable接口]
大概告诉编译器发出一些code,可序列化的一个实例类(我说'可能',因为我不知道C#编译器的内部工作原理)。
Some attributes have special meaning to the C# compiler, for instance the [Serializable]
probably tells the compiler to emit some code that can serialize an instance of the class (I say 'probably' since I do not know the inner workings of the C# compiler).
您也可以创建自己的属性(通过继承 System.Attribute
)。使用反射然后你可以在运行时提取的属性信息。
You can also create your own attributes (by inheriting System.Attribute
). Using reflection you could then at run-time extract information from the attributes.
一个简单的例子是创建一个属性来指定显示一个对象的属性时在HTML表单使用什么样的输入字段。
A simple example would be to create an attribute to specify what kind of input field to use in a HTML form when displaying an object's property.
某些链接:
- Book chapter on attributes
- Attributes overview (MSDN)
- http://stackoverflow.com/search?q=C%23+attributes
- http://www.google.com/search?q=C%23+attributes
这篇关于方括号内文字的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!