通过定义一个属性类,可以创建您自己的自定义属性。该属性类直接或间接地从 Author 属性类:
| C# | 复制代码 |
|---|---|
[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 属性仅在 class 和 struct 声明中有效。
可以按如下所示使用此新属性:
| C# | 复制代码 |
|---|---|
[Author("H. Ackerman", version = 1.1)]
class SampleClass
{
// H. Ackerman's code goes here...
}
| |
AttributeUsage 有一个命名参数 AllowMultiple,使用它可以使自定义属性成为一次性使用或可以使用多次的属性。
| C# | 复制代码 |
|---|---|
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // multiuse attribute
]
public class Author : System.Attribute
| |
| C# | 复制代码 |
|---|---|
[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...
}
| |