方括号之间的文字含义

1

本文介绍了方括号之间的文字含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我见过很多使用 [] 的 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+属性

这篇关于方括号之间的文字含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14