标签:als type 判断 pac 相同 div sum 字符串 ret
项目需要导入Excel,需要对内容进行效验,但是效验的方式都很简单,主要是判断非空字段和应为数字的字段是否为数字。 因为判断的方式大致相同,逐个字段去判断实在太费劲了,所以想到Attribute,可以用这个来实现。
首先是Attribute类
public class CheckAttribute : Attribute
{
/// <summary>
/// 必填级别 1 必填 2 选填 3为后续设计保留字段
/// </summary>
public int NeedType { get; set; }
/// <summary>
/// 限制类型 0 为 字符串 1为int
/// </summary>
public int ContentType { get; set; }
}
然后再类中加上对应的特性,其中Name为必填的字符串 Age为必填的Int Addr为非填的字符串
class TestClass
{
[Check(NeedType = 1, ContentType = 0)]
public string Name { get; set; }
[Check(NeedType = 1, ContentType = 1)]
public int Age { get; set; }
[Check(NeedType = 2, ContentType = 0)]
public string Addr { get; set; }
}
然后再是验证类
public class ValidationModel
{
public bool Validate(object obj)
{
var t = obj.GetType();
var properties = t.GetProperties();
foreach (var property in properties)
{
if (!property.IsDefined(typeof(CheckAttribute), false)) continue;
var attributes = property.GetCustomAttributes(typeof(CheckAttribute), false);
foreach (var attribute in attributes)
{
var needType = (int)attribute.GetType().
GetProperty("NeedType").
GetValue(attribute);
var contentType = (int)attribute.GetType().
GetProperty("ContentType").
GetValue(attribute);
var propertyValue = property.GetValue(obj) as string;
//如果该项为必填,但是值为空则返回错误
if (needType == 1 && string.IsNullOrWhiteSpace(propertyValue))
return false;
//如果值类型为int
if (contentType == 1)
{
//非空字段已被排查,因此该属性可为空,值为空可返回正确信息
if (string.IsNullOrWhiteSpace(propertyValue))
return true;
int temp = 0;
//如果不能被强制转换为float 则类型不为int 返回错误
if (!int.TryParse(propertyValue, out temp))
{
return false;
}
}
}
}
return true;
}
}
在这种类似的有大量相似验证的地方,用Attribute的方式比挨个字段去比较的方式省了很多重复代码,代码可读性也更高
标签:als type 判断 pac 相同 div sum 字符串 ret
原文地址:http://www.cnblogs.com/NEAVERS/p/7112139.html