C# 自定义特性的使用
2015-08-01 10:04
573 查看
自定义特性类必须直接或间接的从 Attribute 派生。
自定义特性类可以添加 AttributeUsageAttribute 特性来限制自定义特性的使用范围。
AttributeUsageAttribute 的使用参照:.NET框架 三种预定义特性的介绍
注意事项:
1、根据约定所有的特性类类名都是以“Attribute”结束,以便将他们和“.NET Framework”中的其他项区别开来。但是,在代码中使用特性时不需要指定attribute后缀。如下面例子所示,我们定义的特性为 AuthorAttribute,使用的时候用 Author 即可。
2、如果特性类包含一个属性,则该属性必须为读写属性。
例:
定义自定义特性:
自定义特性的使用:
假如我们这样使用自定义特性:
编译的时候会提示 “Author特性重复” 错误。因为我们定义的自定义特性的属性:AllowMultiple = false;设为true即可。
自定义特性类可以添加 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即可。
相关文章推荐
- C# 根据KeyEventArgs与组合键字符串相互转换
- C# 根据KeyEventArgs与组合键字符串相互转换
- C#结构体的特点浅析
- C#接口性能测试--计算执行时间
- C#中的线程
- 课堂随笔02--c#中string作为引用类型的特殊性
- 机房重构----C#中将DataTable类型转化为泛型集合
- visual studio 2013中常用的快捷键
- Windows Phone Silverlight 音乐进度条简单实现
- C#处理Excel
- C# 基于正则表达式的字符串验证
- C#使用Dotfuscator混淆代码以及加密
- C#中的自动属性、隐式类型var、对象初始化器与集合初始化器、扩展方法
- C#隐私信息(银行账户,身份证号码,名字)中间部分特殊字符替换(*)
- csharp:Compare two DataTables to rows in one but not the other
- C#打开Powerpoint
- C#导出Word总结
- C#中ListView的简单使用方法
- C#对文件的操作
- 反射(C#)______ITOO项目技术总结(一)