创建自定义特性

可以通过定义特性类(直接或间接 Attribute派生的类)来创建自己的自定义属性,从而快速轻松地识别元数据中的属性定义。 假设你想要用编写该类型的程序员的名称标记类型。 可以定义自定义 Author 属性类:

[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct)
]
public class AuthorAttribute : System.Attribute
{
    private string Name;
    public string Version;

    public AuthorAttribute(string name)
    {
        Name = name;
        Version = "1.0";
    }
}

类名 AuthorAttribute 是属性的名称, Author加上 Attribute 后缀。 它派生自 System.Attribute,因此它是自定义属性类。 构造函数的参数是自定义属性的位置参数。 在此示例中, name 是一个位置参数。 任何公共读写字段或属性都命名为参数。 在这种情况下, version 是唯一命名的参数。 请注意, AttributeUsage 使用特性使 Author 特性仅在类和 struct 声明上有效。

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

[Author("P. Ackerman", Version = "1.1")]
class SampleClass
{
    // P. Ackerman's code goes here...
}

AttributeUsage具有一个命名参数,AllowMultiple,您可以使用该参数将自定义属性设置为单次使用或多次使用。 在以下代码示例中,将创建多用属性。

[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct,
                       AllowMultiple = true)  // Multiuse attribute.
]
public class AuthorAttribute : System.Attribute
{
    string Name;
    public string Version;

    public AuthorAttribute(string name)
    {
        Name = name;

        // Default value.
        Version = "1.0";
    }

    public string GetName() => Name;
}

在下面的代码示例中,将同一类型的多个属性应用于一个类。

[Author("P. Ackerman"), Author("R. Koch", Version = "2.0")]
public class ThirdClass
{
    // ...
}

另请参阅