利用特性扩展元数据Extending Metadata Using Attributes

公共语言运行时使你能够添加类似于关键字的描述性声明(称为特性),以便批注编程元素(如类型、字段、方法和属性)。The common language runtime allows you to add keyword-like descriptive declarations, called attributes, to annotate programming elements such as types, fields, methods, and properties. 编译运行时的代码时,它将被转换为 Microsoft 中间语言 (MSIL),并和编译器生成的元数据一起放置在可移植可执行 (PE) 文件内。When you compile your code for the runtime, it is converted into Microsoft intermediate language (MSIL) and placed inside a portable executable (PE) file along with metadata generated by the compiler. 特性使你能够将额外的描述性信息放到可使用运行时反射服务提取的元数据中。Attributes allow you to place extra descriptive information into metadata that can be extracted using runtime reflection services. 当你声明派生自 System.Attribute 的特殊类的实例时,编译器会创建特性。The compiler creates attributes when you declare instances of special classes that derive from System.Attribute.

.NET Framework 出于多种原因且为解决许多问题而使用特性。The .NET Framework uses attributes for a variety of reasons and to address a number of issues. 特性描述如何将数据序列化、指定用于强制安全性的特征并限制通过实时 (JIT) 编译器进行优化,从而使代码易于调试。Attributes describe how to serialize data, specify characteristics that are used to enforce security, and limit optimizations by the just-in-time (JIT) compiler so the code remains easy to debug. 特性还可记录文件的名称或代码的作者,或控制窗体开发过程中控件和成员的可见性。Attributes can also record the name of a file or the author of code, or control the visibility of controls and members during forms development.

TitleTitle 说明Description
应用特性Applying Attributes 描述如何将特性应用于代码的元素。Describes how to apply an attribute to an element of your code.
编写自定义特性Writing Custom Attributes 描述如何设计自定义特性类。Describes how to design custom attribute classes.
检索存储在特性中的信息Retrieving Information Stored in Attributes 描述如何检索加载到执行上下文中的代码的自定义特性。Describes how to retrieve custom attributes for code that is loaded into the execution context.
元数据和自描述组件Metadata and Self-Describing Components 提供元数据的概述,并说明它是如何在 .NET Framework 可移植可执行 (PE) 文件中实现的。Provides an overview of metadata and describes how it is implemented in a .NET Framework portable executable (PE) file.
如何:将程序集加载到仅反射上下文中How to: Load Assemblies into the Reflection-Only Context 说明如何检索仅反射上下文中的自定义特性信息。Explains how to retrieve custom attribute information in the reflection-only context.

参考Reference

System.Attribute