首页 > 解决方案 > 如何在没有任何框架(没有 asp.net、没有 mvc、没有 ORM)的情况下使用自定义注释验证器 POCO

问题描述

我有一个自定义验证类

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. 收集并打印验证器错误

有没有比这更容易和更内置的东西来阅读这些注释,而不必添加像 (ASP.net / MVC /etc...) 这样的框架 dll?
这仅适用于简单的控制台应用程序。

标签: c#reflectionannotationsattributes.net-attributes

解决方案


我设法让它使用

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库。
它可以与多个[属性]一起使用


推荐阅读