C# 高级特性:属性、不安全代码、预处理指令与 XML 文档
1. 属性(Attributes)
属性是一种语言结构,可用于为代码元素(如程序集、模块、类型、成员、返回值和参数)添加额外信息。
1.1 属性定义
属性的定义格式如下:
[[target:]? attribute-name (
positional-param+ |
[named-param = expr]+ |
positional-param+, [named-param = expr]+)?]
1.2 属性类(Attribute Classes)
属性由直接或间接继承自抽象类 System.Attribute
的类定义。在为元素指定属性时,属性名即为类型名。按照惯例,派生类型名以 Attribute
结尾,但指定属性时可不加此后缀。例如:
[Serializable]
public class Foo {...}
这里的 Serializable
属性实际上是 System
命名空间中声明的一个类型:
class SerializableAttribute : Attribute {...}
也可以使用其全