C#,.net使用特性类,将json转为实体时验证字段

  1. 创建实体模型

     实体模型使用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; }  //用于验证浮点类型范围
  1. 使用反射遍历实体的每一个字段

    封装一个验证方法传入实体
    
		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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值