通过特性+反射 实现对属性int值范围的检测
2017-02-25 14:57
295 查看
public class IntCheckAttribute : Attribute { private int _Min = 0; private int _Max = 100; public IntCheckAttribute(int min, int max) { this._Min = min; this._Max = max; } public bool Check(int ivalue) { return ivalue > this._Min && ivalue < this._Max; } } public class User { [IntCheck(0, 1000)]//范围0-1000 public int ID { get; set; } //不写其余属性了 } //插入类 public static class SaveFun { /// <summary> /// 插入方法 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="t">要插入的对象</param> public static void Save<T>(this T t) where T : new() { bool IsOk = true; //获取类型 Type type = t.GetType(); //获取类型中的属性 PropertyInfo[] ps = type.GetProperties(); //遍历数组 foreach (var prop in ps) { //获取该数组的特性集合 List<Attribute> aList = prop.GetCustomAttributes().ToList(); //遍历特性 foreach (var attr in aList) { if (attr is IntCheckAttribute) { //创建对象 IntCheckAttribute intc = attr as IntCheckAttribute; //通过对象方法 和反射获取属性值 获取是否符合要求 IsOk = intc.Check((int)prop.GetValue(t)); } } if (!IsOk) { //如果有错误,直接跳出 不存储 break; } } if (IsOk)//符合条件 { Console.WriteLine("数据符合条件,插入数据库"); } else { Console.WriteLine("数据不符合规范,禁止插入"); } } }
调用
Console.WriteLine("***********下面是ID=50情况下************"); User u = new User(); u.ID = 50; u.Save<User>(); Console.WriteLine("***********下面是ID=99999999情况下************"); User u1 = new User(); u1.ID = 99999999; u1.Save<User>();
结果
相关文章推荐
- 通过反射得到绑定在类的属性上的特性信息
- 通过Android的反射机制实现系统属性的设置和获取
- Android-->检测内置/外置SD卡存储卡,枚举所有挂载点(通过反射实现),监听SD卡广播
- 通过反射获取特性属性Id
- 在设计时通过反射改变属性的特性
- 3 手写实现SpringMVC,第三节:通过反射给属性和参数注入值
- java反射获取实体类的属性名和值通过POI导出EXCEl,并实现表格列宽度自适应
- 关于通过注解反射实现findViewById(int x);的原理
- 练习2-1 编写一个程序一确定分别由signed及unsigned限定的char,short,int及long类型变量的取值范围。采用打印标准头文件中的相应值以及直接计算两种方式实现。通过直接计算来确定浮点类型的取值范围是一项难度很大的任务。
- 通过反射,将datatable转换为List集合(反射读取实体类的属性,并赋值),通过接口来实现MySql和MsSql数据的切换(二层反射),静态构造函数,抽象类和接口的区别
- C#中的特性 和 通过反射获取属性上的特性
- 在C#中如何实现枚举类型的特性扩展和反射获取
- C#中通过反射查看程序集的特性信息
- WPF下通过附加属性实现单实例启动
- 通过反射来判断某个程序集中是否有实现该接口的类
- 通过timer控件和窗体的opacity属性,轻松实现窗体的淡入淡出
- 通过反射来实现:DataTable 和List 相互转换
- pojo类的属性与数据库表字段名一样时,java通过反射拼凑出相应的sql.
- C# 能否实现像枚举一样自反射元数据属性的功能。
- 利用反射+特性实现简单的实体映射数据库操作类(还未做自动生成SQL语句部分)