您的位置:首页 > 编程语言 > C#

C# 自定义特性的使用

2015-08-01 10:04 573 查看
自定义特性类必须直接或间接的从 Attribute 派生。
自定义特性类可以添加 AttributeUsageAttribute 特性来限制自定义特性的使用范围。

AttributeUsageAttribute 的使用参照:.NET框架 三种预定义特性的介绍

注意事项:
1、根据约定所有的特性类类名都是以“Attribute”结束,以便将他们和“.NET Framework”中的其他项区别开来。但是,在代码中使用特性时不需要指定attribute后缀。如下面例子所示,我们定义的特性为 AuthorAttribute,使用的时候用 Author 即可。
2、如果特性类包含一个属性,则该属性必须为读写属性。

例:

定义自定义特性:
[AttributeUsage(System.AttributeTargets.All, AllowMultiple = false, Inherited = false)]
public class AuthorAttribute : System.Attribute
{
private string name;
public double version;

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


自定义特性的使用:
[Author("李四", version = 1.2)]
public class SampleClass
{
public void SampleMethod() { }
}


假如我们这样使用自定义特性:
[Author("张三", version = 1.1)]
[Author("李四", version = 1.2)]
public class SampleClass
{
public void SampleMethod() { }
}


编译的时候会提示 “Author特性重复” 错误。因为我们定义的自定义特性的属性:AllowMultiple = false;设为true即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: