如何存储来自通用对象的验证器列表。 C#

时间:2018-08-12 17:31:58

标签: c# validation user-input

我正在为我的API开发输入验证库。

until pipe1r.eof?

并且正在尝试验证

interface IValidation<T>{
    List<string> Errors(); 
    bool Valid(T input);
}

class GuidValidator: IValidation<Guid> {
    bool Valid(Guid input){ ... }
}

class StringLengthValidator: IValidation<String> {
    bool Valid(String input){ ... }
}

来自控制器

class MyInputToValidate {
    public Guid Id {get;set;}
    public string Name {get;set;}
    public string Description {get;set;}
}

但是我很难将验证器保存到字典中以备后用。

class MyController { 
    public ActionResult Post([FromBody] MyInputToValidate body){
        ValidatorCollection validators = new ValidatorCollection<MyInputToValidate>();

        validators.AddValidator(i => i.Id, new GuidValidator());
        validators.AddValidator(i => i.Name, new LengthValidator());
        validators.AddValidator(i => i.Description, new LengthValidator());

        bool valid = validators.Validate(body);

        //...
    }
}

我收到interface IValidatorCollection<T> { void AddValidator<TProperty>( Expression<Func<T, TProperty>> property, IValidator<TProperty> validator ); bool Validate(T value); } class ValidatorCollection: IValidatorCollection<T> { private IDictionary<string, IValidator<object>> _validators = new Dictionary<string, IValidator<object>>(); public void AddValidator<TProperty>(Expression<Func<T, TProperty>> property, IValidator<TProperty> validator) { _validators.Add(property.Name, validator); } public bool Validate(T value) { foreach(var val in _validators){ bool valid = val.Value.Valid(value); } //... } } 行的错误IValidator<TProperty> is not assignable to to IValidator<object>。我尝试过类型转换_validators.Add(property.Name, validator);,但收到运行时错误(IValidator<object>validator)。如何存储通用对象属性的验证器列表?

0 个答案:

没有答案