-
创建实体模型
实体模型使用C#提供的现有类RequiredAttribute 该类位于命名空间using System.ComponentModel.DataAnnotations下 引用命名空间using System.ComponentModel.DataAnnotations;
[Required(ErrorMessage = "库位ID不能为空")]
public int PlanID { get; set; } //验证非空
[Range(0, 10000, ErrorMessage = "长度异常")]
public float UpLength { get; set; } //用于验证浮点类型范围
public static string Validate<T>(this T t)
{
Type type = t.GetType();
//获取所有属性
PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
List<string> errorList = new List<string>();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (propertyInfo.IsDefined(typeof(ValidationAttribute)))//如果属性上有定义该属性,此步没有构造出实例
{
foreach (ValidationAttribute attribute in propertyInfo.GetCustomAttributes(typeof(ValidationAttribute)))
{
if (!attribute.IsValid(propertyInfo.GetValue(t, null)))
{
errorList.Add($"[{propertyInfo.Name}]" + attribute.ErrorMessage);
}
}
}
}
return string.Join(",", errorList);
}
也可自己继承Attribute类或ValidationAttribute类,写特性,
在反射遍历实体的时候将ValidationAttribute替换为自己写特性类就行
重写特性参考其他博客 博客园https://www.cnblogs.com/fnz0/p/11387835.html