Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c# - Meaning of text between square brackets

I have seen a lot of C# programs that use the [], for example [STAThread] and then the code follows. Another classic example is [DLLImport].

I know what STAThread means but my question is what is the significance of the square brackets, essentially what do they tell the compiler?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's an attribute. Attributes are a form of metadata that you can attach to various code elements: classes, methods, assemblies etc.

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).

You can also create your own attributes (by inheriting System.Attribute). Using reflection you could then at run-time extract information from the attributes.

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.

Some links:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...