Meaning of text between square brackets

后端 未结 5 1563
孤街浪徒
孤街浪徒 2020-12-16 16:17

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

5条回答
  •  感动是毒
    2020-12-16 16:50

    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:

    • Book chapter on attributes
    • Attributes overview (MSDN)
    • https://stackoverflow.com/search?q=C%23+attributes
    • http://www.google.com/search?q=C%23+attributes

提交回复
热议问题