委托和查询谓词 [英] Delegates and Predicate enquiry

查看:101
本文介绍了委托和查询谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解lambda表达式,我试图了解为什么,虽然具有EmployeeFilterAge类,像这样:

I'm learning about lambdas and I'm trying to understand why, while having EmployeeFilterAge class like so:

public class EmployeeFilterAge
{
    int _age;
    public EmployeeFilterAge(int age)
    {
        _age = age;
    }
    public bool OlderThan(Employee employee)
    {
        return employee._age > _age;
    }
}

当我试图做到这一点:

var filterByAge = new EmployeeFilterAge(29);
var del = new AgeExclusion(filterByAge.OlderThan);



我得到一个错误说不重载方法匹配... ...委托,而代表看起来像:

I get an error saying "no overload method ... matches delegate ...", while delegate looks like that:

public delegate bool AgeExclusion(object person);



这是因为它的谓词?

Is this because its a predicate?

推荐答案

委托说,参数可以是任何类型的。当有人调用方法,他们可以在一个狮子,老虎,熊(噢,我的!),或者其他任何他们想要的,你的方法需要能够处理它传递。

The delegate says that the parameter can be of any type. When someone invokes the method they can pass in a Lion, a Tiger, a Bear (Oh My!!!), or whatever else they want, and your method needs to be able to handle it.

您正试图分配一个永远只能接受一个方法的员工,那是不允许接受任何其他类型作为参数,所以很明显它不是分配给委托类型的变量的一种有效方法。

You're trying to assign a method that can only ever accept an Employee, and that isn't allowed to accept any other type as an argument, so obviously it's not a valid method to assign to a variable of that delegate type.

现在如果类型互换,这将是罚款。如果代表说,它可以接受,需要一个方法只有一个员工作为参数,那么你可以把它认为是能够利用的什么方法作为参数,因为毕竟,所有的员工,它会通过,这将是一个方法有效参数,可以接受的任何的。这种情况的技术术语是逆变。

Now if the types were reversed, it would be fine. If the delegate said that it could accept a method that takes only an Employee as an argument, then you could give it a method that is able to take anything as an argument, because after all, all of the employees that it will pass it would be valid arguments for a method that can accept anything. The technical term for this is contravariance.

这篇关于委托和查询谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆