簡體   English   中英

如何在沒有任何框架的情況下使用自定義注釋驗證器POCO(沒有asp.net,沒有mvc,沒有ORM)

[英]How to use a custom annotations validator POCO without any framework (no asp.net, no mvc, no ORM)

我有一個自定義驗證類

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. 調用Validate函數
  5. 收集並打印驗證程序錯誤

有沒有比這更容易和更內置的東西,用於閱讀這些注釋,而不必添加像(ASP.net / MVC / etc ...)這樣的框架dll?
這僅適用於簡單的控制台應用程序。

我設法使用它

using System.ComponentModel.DataAnnotations;

class RequiredAttribute : ValidationAttribute
{ //... above code }

在主要的Driver類......

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庫。
它可以使用多個[屬性]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM