c# - 如何在没有任何框架(没有 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 个......)
- 调用验证函数
- 收集并打印验证器错误
有没有比这更容易和更内置的东西来阅读这些注释,而不必添加像 (ASP.net / MVC /etc...) 这样的框架 dll?
这仅适用于简单的控制台应用程序。
解决方案
我设法让它使用
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
库。
它可以与多个[属性]一起使用
推荐阅读
- javascript - Monaco 如何实现语法高亮等样式?
- javascript - 来自 HTML 的嵌套对象?
- python - 神器提要 python twine 找不到它
- c - 如何计算打开的窗口(cmd.exe)的数量?
- bash - 在执行 docker build > CMD 时重定向 stdout 和 stderr
- javascript - 在不同浏览器中将UTC时间转换为本地时间
- php - 前端订单详情中的 API 跟踪代码集成 (Woocommerce)
- webix - 日期格式 webix 数据表过滤器
- swift - SideMenu 单独出现在更新的 macOS catalina 和更新的 Xcode 11.2.1 中
- node.js - Apollo Server Express + 订阅错误