【Attribute】⾃定义ValidationAttribute+扩展⽅法实现类对象
字段数据验证
常常有这样的需求:⽅法接受⼀个对象参数,要验证对象的所有字段的值是否合乎要求,如进⾏⾮空检测,长度检测等等。
⽐如,有这样⼀个Stu的类
public class Stu
{
public string Name { get; t; }
public int Age { get; t; }
public byte[] FileBytes { get; t; }
}
new ⼀个 对象 作为参数进⾏传递
小梅与牧羊犬
static void Main(string[] args)
{
Stu student = new Stu()
{
Age = 45,
FileBytes = new Byte[1024 * 10000]
};
新大头儿子小头爸爸第二季//……要在这⾥检测student对象的各个属性值是否合法……
Console.ReadKey();
}
怎么来判断student的合法性呢?检测student的Name字段是否有值,检测FileBytes字段是否超出指定长度
引⽤System.ComponentModel.DataAnnotations,在Stu类的Name字段上加上[Required]属性标签
检测FileBytes的长度,需要⾃定义来实现
定义⼀个ByteArrayMaxSizeCheckAttribute⾃定义属性类,继承⾃ValidationAttribute,如下
public class ByteArrayMaxSizeCheckAttribute : ValidationAttribute
{
///<summary>
///最⼤⼤⼩
///</summary>
private int maxsize;
public ByteArrayMaxSizeCheckAttribute()
{
}
public ByteArrayMaxSizeCheckAttribute(int size)
{
maxsize = size;
}
public override bool IsValid(object value)
{
if (value == null)筋疲力尽造句
{
牛奶炖鸡蛋return true;
}
var content = value as byte[];
double filesize = content.Length / 1024 * 1.0;
filesize = filesize / 1024 * 1.0;
if (filesize > maxsize)
{
return fal;
}血癌
el
{
return true;
}
}
}
然后,同样,在Stu类的FileBytes字段上加上两个标签
[Required]
[ByteArrayMaxSizeCheck(1, ErrorMessage = "{0}⼤⼩超出最⼤限制")]
Stu就应该是下⾯的样⼦
public class Stu
{
[Required]孕妇煲汤食谱大全
public string Name { get; t; }
public int Age { get; t; }
[Required]
[ByteArrayMaxSizeCheck(1, ErrorMessage = "{0}⼤⼩超出最⼤限制")] public byte[] FileBytes { get; t; }
}
public static class ValidExtension
{
public static string ErrorMsg<T>(this T model) where T : class, new()
{
var propertis = model.GetType().GetProperties();
string errorMsg = "";
foreach (var info in propertis)
{
var attributes = info.GetCustomAttributes();
foreach (var attribute in attributes)
{
if (attribute is ValidationAttribute)
{
var reqattr = attribute as RequiredAttribute;
var maxsizeattr = attribute as ByteArrayMaxSizeCheckAttribute;
if (reqattr != null)
{
var obj = info.GetValue(model);
if (!reqattr.IsValid(obj))龙舟竞赛
{
errorMsg = errorMsg + reqattr.FormatErrorMessage(info.Name);
}
}
if (maxsizeattr != null)
{
var obj = info.GetValue(model);
if (!maxsizeattr.IsValid(obj))
{
errorMsg = errorMsg + maxsizeattr.FormatErrorMessage(info.Name); }
}
}
}
}
return errorMsg;
}
}
static void Main(string[] args)
{
Stu student = new Stu()
{
Age = 45,
FileBytes = new Byte[1024 * 10000]
};
var errorMessage = student.ErrorMsg();
Console.WriteLine(errorMessage);
Console.ReadKey();
}
孔卡翻译