【发布时间】:2018-09-14 11:08:03
【问题描述】:
我真的很难为 FluentValidator 创建基于接口/约定的规则。它有以下类
abstract class AbstractValidator<T>
{
IRuleBuilderInitial<T, TProperty> RuleFor<TProperty>(Expression<Func<T, TProperty>> expression)
...
}
public interface IWithPropertyA
{
string PropertyA{get;set;}
}
public interface IWithPropertyB
{
string PropertyB{get;set;}
}
public class Handler1Data: IWithPropertyA
{
public string PropertyA {get;set;}
}
public class Handler2Data: IWithPropertyA, IWithPropertyB
{
public string PropertyA {get;set;}
public string PropertyB {get;set;}
}
public class Handler1 : AbstractValidator<Handler1Data> {}
public class Handler2 : AbstractValidator<Handler2Data> {}
我正在尝试创建扩展方法,该方法基本上会检查泛型参数是否实现特定接口,然后向其添加规则:
public static void ValidateAll<T>(this AbstractValidator<T> validator)
{
(validator as AbstractValidator<IWithPropertyA>)?.RuleFor(x => x.PropertyA).NotEmpty().WithMessage("PropertyA Missing");
(validator as AbstractValidator<IWithPropertyB>)?.RuleFor(x => x.PropertyB).NotEmpty().WithMessage("PropertyB Missing");
}
这里的问题显然是 AbstractValidator 不是协变的,因此验证器既不能转换为 AbstractValidator<PropertyA> 也不能转换为 AbstractValidator<PropertyB>。我尝试创建自己的 Base Validator,如下所示,然后基于此创建扩展方法,但我做不到。
public interface IMyValidator<in T>
{
void AddMyRule<TProperty>(Expression<Func<T, TProperty>> expression) //it doesn't work because Expression<Func<T,Property> cannont be covariant
}
public abstract class MyBaseValidator<T>: AbstractValidator<T> ,IMyValidator<T>
{
void AddMyRule<TProperty>(Expression<Func<T, TProperty>> expression)
}
每个 Handler 都会像这样调用方法:
public class Handler1 : AbstractValidator<Handler1Data> {
this.ValidateAll();
}
【问题讨论】:
标签: c# covariance contravariance