-
ASP.net教程之.Net 特性 attribute 学习 ----自定义特性
什么是特性?[Obsolete("不要用无参构造函数",true)] 放在方式上, 该方法就不能使用了[Serializable]放在类上面。该类就是可以序列化和反序列化使用了。在命名空间、类、方法、属性、字段、枚举 上用中括号[]自定义特性,特性就是类:必须继承Attribute 或者是Attribute的泛生类public class SizeAttribute : Attribute // 这个就是一个自定义特性{public SizeAttribute(){Console.WriteLine("这是一个SizeAttribute的构造函数");}}这个特性就创建好了在其他类, 如Student类上[SizeAttribute] //在类上写特性public class Student{[SizeAttribute] //在属性上写特性public int Id{set; get;}public string Name{set;get}[SizeAttribute] //在方法上写特性public void Show(){Console.WriteLine("Show")}}当然特性 也可以有描述自己特性的办法就是在特性上面写上[AttributeUsage(AttributeTargets.All,AllowMultiple =false,Inherited =true)]public class SizeAttribute : Attribute{}//意思是当前特性包含所有类型都可以使用,只能单一使用,可以继承特性:1.当程序编译和执行,特性和注释的效果是一样的,没有任何不同2.特性编译后是metadata,只有在反射的时候,才能使用特性。3.特性可以做权限检测,属性验证,封装枚举等很多功能。4.特性是一个类,可以用作标记元素,编译时生成在metadata里,平时不影响程序的运行,除非主动用反射去查找,可以得到一些额外的信息和操作,提供了更丰富扩展空间,特性可以在不 破坏类型封装的前提下,额外增加功能。例子:有一个学生类,希望用特性,让添加的学生年龄不能小于12岁,大于20岁//学生类public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[Obsolete("不要用无参构造函数",true)] //这个特性,是不能使用无参构造函数
public Student()
{ }
public Student(int id, string name,int age)
{
this.Id = id;
this.Name = name;[ControlAgeAttribute(_vMin=12,_vMax=30)] //要判断年龄,年龄小于20,大于12, 就将下面自定义的特性放在这个属性上面
this.Age = age;
}
public void Show()
{
Console.WriteLine("这个show方法");
}
}//控制年龄的特性 :特性的命名规范--名称后面为Attributepublic class ControlAgeAttribute : Attribute{public int _vMin{get;set;}//最小年龄public int _vMax{get;set;} //最大年龄public bool CompareAge(int age){return age>_vMin && age <_vMax ? true : false; //}}//反射使用特性---用静态方法public static class Manage{public static bool CompareAgeManage(this Student stu){bool result = false;Type type = typeof(stu);//先获取类型ProperyInfo prop = type.GetProperty("Age");//反射获取年龄属性
if (prop.IsDefined(typeof(ControlAgeAttribute ),true))//判断当前属性是否有ControlAgeAttribute 的特性{ControlAgeAttribute attribute = (ControlAgeAttribute) prop.GetCustomAttribute(typeof(ControlAgeAttribute ),true);//获取特性result = attribute.CompareAge(stu.Age);return result;//得到结果返回}
return result;}}//控制台Main方法里面执行static void Main(string[] args)
{
Student student = new Student(12,"hahaha",15);
Console.WriteLine(student.CompareAgeManage()); //15在12和20 之间,所以是True;
}
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能