【发布时间】:2019-06-14 01:07:15
【问题描述】:
我有以下代码,我正在尝试为我的域对象编写通用验证规则。这样做时,我遇到了处理 Func 委托支持差异的问题
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) ;
}
}
使用上面的代码,编译器会给出一条错误消息
在线编译器错误:base.AddValidationRule(empPredicate); 参数 1:无法从 'System.FuncEmployee, bool>' 转换为 'System.FuncPerson, bool>
我已经提到了这个https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/dd465122%28v%3dvs.100%29,但我仍然无法让编译器理解这里的逆变,
感谢您的帮助,让我更好地理解这一点
【问题讨论】:
-
您缺少代码,我无法重现问题。
-
Func<>确实是一个逆变,但您正试图将其用作协变
标签: c# .net-core asp.net-core-2.1 generic-variance