问题描述
我有以下代码段,试图为我的域对象编写通用验证规则.在这样做的时候,我遇到一个问题来解决Func代表支持差异的问题
I have the following piece of code where I am trying to write a generic validation rule for my domain objects. while doing so I have an issue to deal Func delegate supporting variance
public class Person { }
public class Employee : Person { }
internal interface IValidation<T> where T: Person
{
void AddValidationRule(Func<T,bool> predicateFunction);
}
internal class BaseValidation : IValidation<Person>
{
void IValidation<Person>.RegisterValidationRules(Person person)
{
}
}
internal class EmployeeValidation : BaseValidation
{
void RegisterValidation()
{
Func<Employee,bool> empPredicate = CheckJoiningDate;
base.AddValidationRule(empPredicate);
}
bool CheckJoiningDate(Employee employee)
{
return employee.JoiningDate > DateTime.Now.AddDays(-1) ;
}
}
使用上面的代码,编译器会显示一条错误消息
With the above code in place, compiler gives an error message saying
我已提到 https://docs.microsoft.com/zh-cn/previous-versions/visualstudio/visual-studio-2010/dd465122%28v%3dvs.100%29 但我仍然无法使得编译器在这里了解这种矛盾,
I had referred to this https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/dd465122%28v%3dvs.100%29 but I still couldn't make the compiler to understand about the contravariance here,
感谢您的帮助,以便我更好地理解
Appreciate your help so I understand this better
推荐答案
base.AddValidationRule
需要一个可以在任何 Person
上运行的函数.您的函数只能在限制更严格的 Exployee
上运行.这是错误的方差形式.
base.AddValidationRule
requires a function that can operate on any Person
. Your function can only operate on Exployee
which is more restrictive. This is the wrong form of variance.
此处未显示,但可能是 BaseValidation
实现的 IValidation< Person>
.
It is not shown here but likely BaseValidation
implemented IValidation<Person>
.
最好的解决方法是确保您从 IValidation< Employee>
继承,这可以通过使 BaseValidation
通用来实现.
Likely, the best fix is to ensure that you inherit from IValidation<Employee>
, possibly by making BaseValidation
generic.
这项工作可以吗?
internal class BaseValidation<T> : IValidation<T>
{
void IValidation<T>.RegisterValidationRules(T entity)
{
}
}
internal class EmployeeValidation : BaseValidation<Employee>
{
//...
}
这篇关于.net核心中的Func委托如何使用协变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!