通过定义一个属性类,可以创建您自己的自定义属性。该属性类直接或间接地从 Attribute 派生,有助于方便快捷地在元数据中标识属性定义。假设您要用编写类或结构的程序员的名字标记类和结构。可以定义一个自定义 Author 属性类:

C# CopyCode image复制代码
[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct)
]
public class Author : System.Attribute
{
    private string name;
    public double version;

    public Author(string name)
    {
        this.name = name;
        version = 1.0;
    }
}

类名是属性名 Author。它由 System.Attribute 派生而来,因此是自定义属性类。构造函数的参数是自定义属性的定位参数(在本例中为 name),任何公共读写字段或属性都是命名参数(在本例中,version 是唯一的命名参数)。请注意 AttributeUsage 属性的用法,它使得 Author 属性仅在 classstruct 声明中有效。

可以按如下所示使用此新属性:

C# CopyCode image复制代码
[Author("H. Ackerman", version = 1.1)]
class SampleClass
{
    // H. Ackerman's code goes here...
}

AttributeUsage 有一个命名参数 AllowMultiple,使用它可以使自定义属性成为一次性使用或可以使用多次的属性。

C# CopyCode image复制代码
[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct,
                       AllowMultiple = true)  // multiuse attribute
]
public class Author : System.Attribute
C# CopyCode image复制代码
[Author("H. Ackerman", version = 1.1)]
[Author("M. Knott", version = 1.2)]
class SampleClass
{
    // H. Ackerman's code goes here...
    // M. Knott's code goes here...
}

Expand image请参见