您的位置:首页 > 其它

通过特性+反射 实现对属性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>();


结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐