【问题标题】:How to use a custom annotations validator POCO without any framework (no asp.net, no mvc, no ORM)如何在没有任何框架(没有 asp.net、没有 mvc、没有 ORM)的情况下使用自定义注释验证器 POCO
【发布时间】:2019-09-20 10:56:48
【问题描述】:

我有一个自定义验证类

using System;
using System.Collections.Generic;
using System.Reflection;

 internal class RequiredAttribute1 : Attribute
{
    public RequiredAttribute1()
    {
    }

    public void Validate(object o, MemberInfo info, List<string> errors)
    {
        object value;

        switch (info.MemberType)
        {
            case MemberTypes.Field:
                value = ((FieldInfo)info).GetValue(o);
                break;

            case MemberTypes.Property:
                value = ((PropertyInfo)info).GetValue(o, null);
                break;

            default:
                throw new NotImplementedException();
        }

        if (value is string && string.IsNullOrEmpty(value as string))
        {
            string error = string.Format("{0} is required", info.Name);

            errors.Add(error);
        }
    }
}

我在以下对象上使用它:-

class Fruit
{
 [RequiredAttribute1]
 public string Name {get; set;}

 [RequiredAttribute1]
 public string Description {get; set;}
}

现在,我想对水果列表运行验证规则,以打印到字符串
我能想到的只有:-

  1. 遍历水果
  2. 对于每个水果,遍历其属性
  3. 对于每个属性,迭代自定义验证器(这里只有 1 个...)
  4. 调用验证函数
  5. 收集并打印验证器错误

有没有比这更简单、更内置的方法来读取这些注释,而无需添加框架 dll,例如 (ASP.net / MVC /etc...)?
这只是一个简单的控制台应用程序。

【问题讨论】:

    标签: c# reflection annotations attributes .net-attributes


    【解决方案1】:

    我设法让它工作了

    using System.ComponentModel.DataAnnotations;
    
    class RequiredAttribute : ValidationAttribute
    { //... above code }
    

    在主驱动类中...

    using System.ComponentModel.DataAnnotations;
    
    class Driver
    {
    
    public static void Main(string[] args)
    {
                var results = new List<ValidationResult>();
                var vc = new ValidationContext(AreaDataRow, null, null);
                var errorMessages = new List<string>();
    
                if (!Validator.TryValidateObject(AreaDataRow, vc, results, true))
                {
                    foreach (ValidationResult result in results)
                    {
                        if (!string.IsNullOrEmpty(result.ErrorMessage))
                        {
                            errorMessages.Add(result.ErrorMessage);
                        }
                    }
    
                    isError = true;
                }
    }
    }
    

    无需框架或 ORMS,只需 DataAnnotations 库即可。
    它可以与多个[属性]一起使用

    【讨论】:

      猜你喜欢
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多