逆变如何与 .net 核心中的 Func 委托一起使用 [英] How does contravariance work with Func delegate in .net core
问题描述
我有以下一段代码,我正在尝试为我的域对象编写通用验证规则.这样做时,我有一个问题来处理 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
在线编译器错误:base.AddValidationRule(empPredicate);参数 1:无法从 'System.Func<>Employee, bool>' 转换为'System.Func<>Person, bool>
Compiler Error on line : base.AddValidationRule(empPredicate); Argument 1: cannot convert from 'System.Func<>Employee, bool>' to 'System.Func<>Person, bool>
我提到了这个 https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/dd465122%28v%3dvs.100%29 但我还是做不到't 让编译器理解这里的逆变,
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
推荐答案
无法从 'System.Func<>Employee, bool>' 转换为 'System.Func<>Person, bool>
cannot convert from 'System.Func<>Employee, bool>' to 'System.Func<>Person, bool>
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
.
It is not shown here but likely BaseValidation
implemented IValidation<Person>
.
可能,最好的解决方法是确保您从 IValidation
继承,可能是通过使 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 委托一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!