问题描述
我见过很多使用 []
的 C# 程序,例如 [STAThread]
然后代码如下.另一个经典的例子是[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?
推荐答案
这是一个属性.属性是一种元数据形式,您可以将其附加到各种代码元素:类、方法、程序集等.
It's an attribute. Attributes are a form of metadata that you can attach to various code elements: classes, methods, assemblies etc.
某些属性对 C# 编译器具有特殊意义,例如 [Serializable]
可能会告诉编译器发出一些可以序列化类实例的代码(我说可能",因为我不知道 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.
一些链接:
- 关于属性的书籍章节
- 属性概述 (MSDN)
- https://stackoverflow.com/search?q=C%23+attributes李>
- http://www.google.com/search?q=C%23+属性
这篇关于方括号之间的文字含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!