【发布时间】: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 个...)
- 调用验证函数
- 收集并打印验证器错误
有没有比这更简单、更内置的方法来读取这些注释,而无需添加框架 dll,例如 (ASP.net / MVC /etc...)?
这只是一个简单的控制台应用程序。
【问题讨论】:
标签: c# reflection annotations attributes .net-attributes