-
创建实体模型
实体模型使用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