c#特性简述使用
来源:互联网 发布:java脱壳工具 编辑:程序博客网 时间:2024/06/06 17:07
什么是特性?
定义:特性本质上也是有一种类,通过添加特性,就可以实例化这个特性类;
直接进入正题,特性大致可以分为两种:
一:系统自带的特性
二:自定义特性
我们主要讲一下如何自定义特性,定义的方式和普通的类定义方式一致,但是,
第一:需要继承标准特性类
第二:需要添加标准特性,用来限制特性的使用范围等
第三:必须要定义构造函数,即使是空的
如下:
定义:特性本质上也是有一种类,通过添加特性,就可以实例化这个特性类;
直接进入正题,特性大致可以分为两种:
一:系统自带的特性
二:自定义特性
我们主要讲一下如何自定义特性,定义的方式和普通的类定义方式一致,但是,
第一:需要继承标准特性类
第二:需要添加标准特性,用来限制特性的使用范围等
第三:必须要定义构造函数,即使是空的
如下:
[AttributeUsage(AttributeTargets.All,AllowMultiple = true, Inherited=true)] //基于标准特性class CustomAttr:Attribute //继承标准特性类{ //0参数构造函数 public CustomAttr() { }//3个参数构造函数public CustomAttr(string name, int sore,string message) { this.name = name; this.sore = sore; this.message = message; } public string name { get; set; } public int sore { get; set; } public string message { get; set; }}使用特性例子如下:(这里相当于实例化了2个类)[CustomAttr(name ="dj",sore=100,message ="222")][CustomAttr(name = "sq", sore = 100, message = "666")]class Test{}注意:
[CustomAttr(name ="dj",sore=100,message ="222")], 这里相当于调用了不带任何参数的构造函数,但是使用属性功能进行赋值
[CustomAttr("dj,100,"666")], 这里相当于直接调用了带有三个参数的构造函数
这就是为什么我们必须要给自定义特性类添加构造函数的原因
实测:static void Main(string[] args){ System.Reflection.MemberInfo info = typeof(Test); var customAttrLsit = Attribute.GetCustomAttributes(info, typeof(CustomAttr)) as CustomAttr[]; for (int i = 0; i < customAttrLsit.Count(); i++) { Console.WriteLine("================================================"); Console.WriteLine("创建人:{0}", customAttrLsit[i].name); Console.WriteLine("创建时间:{0}", customAttrLsit[i].sore); Console.WriteLine("备注消息:{0}", customAttrLsit[i].message); } Console.ReadKey();}
使用特性可以方便的为我们给类和方法加上从元数据!
阅读全文
0 0
- c#特性简述使用
- C#3.0新特性简述
- C99特性简述
- 汽车总线特性简述
- 汽车总线特性简述
- ES6特性简述
- C#使用反射访问特性
- C# 自定义特性的使用
- C#反射,特性结合使用
- 简述iOS8的新特性
- Java之final特性简述
- Java之final特性简述
- ECMAScript6的新特性简述
- ECMAScript6的新特性简述
- c# 特性/属性(Attribute) 以及使用反射查看自定义特性
- c# 特性/属性(Attribute) 以及使用反射查看自定义特性
- C#定制特性的使用(2010070809)
- C# 使用自定义的特性Attribute
- Qt和VTK等一些编程技巧
- 文章标题
- C# 文件的输入与输出
- 表扩展方案
- Spring boot + shiro 跨域配置(解决jsessionid丢失问题)
- c#特性简述使用
- JS同时验证固话和手机号正则表达式
- buildroot重新编译package
- Linux学习(Make和Makefile)
- LeetCode142. Linked List Cycle II
- 心得
- SQLAlchemy使用笔记一
- Android基础——Tween动画、Drawable动画、Property动画、MaterialDesign动画、Trasition动画
- Spring 事物的配置以及容易出现的错误