c# - 谓词的委托(delegate)不起作用

标签 c# lambda delegates

我倾向于 delagate 和 lambda 表达式。我写了一些测试代码,使用 Count(),一些调用工作,但最后没有工作,我不知道为什么。请帮我解释一下。谢谢。

public static int Count<T>(T[] arr, Predicate<T> condition)
{
    int counter = 0;
    for (int i = 0; i < arr.Length; i++)
        if (condition(arr[i]))
            counter++;
    return counter;
}

delegate Boolean IsOdds<T>(T x);
delegate bool IsEven(int x);

private void button1_Click(object sender, EventArgs e)
{
    IsOdds<int> isOdds = i => i % 2 == 1;//must be <int>, not <T>
    IsEven isEven = i => i % 2 == 0;            

    Action<int> a = x => this.Text = (x*3).ToString();
    a(3);

    Predicate<int> f = delegate(int x) { return x % 2 == 1; };
    Predicate<int> ff = x => x % 2 == 1;

    MessageBox.Show("lambada " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, x => x % 2 == 1).ToString());
    MessageBox.Show("f " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, f).ToString());
    MessageBox.Show("ff " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, ff).ToString());
    MessageBox.Show("delegate " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, delegate(int x) { return x % 2 == 1; }).ToString());
    MessageBox.Show(Count<int>(new int[] { 1, 2, 3, 4, 5 }, isOdds(int x)).ToString());  //this is wrong
    MessageBox.Show(Count<int>(new int[] { 1, 2, 3, 4, 5 }, isEven(int x)).ToString());  //this is wrong
    return;
}

最佳答案

Count<int>(new int[] { 1, 2, 3, 4, 5 }, isOdds(int x));

这是无效的。 isOdds 返回 bool 并采用整数,它必须像 Predicate<int> .但是您不能直接发送,因为它们不是同一类型。你必须使用另一个 lambda。

Count<int>(new int[] { 1, 2, 3, 4, 5 }, x => isOdds(x)); // x => isOdds(x) is now type of Predicate<int>

对于 isEven 也是一样

还有一种方法。你可以创建新的谓词。

Count<int>(new int[] { 1, 2, 3, 4, 5 }, new Predicate<int>(isOdds)); 

关于c# - 谓词的委托(delegate)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33162788/

相关文章:

c# - 使用 Entity Framework 创建SQLite数据库

c# - CSV 下载为 HTM

python - 在python中有一个列表,使用lambda和map/filter生成新列表

ruby - Lambda 和 proc 生成

c# - CreateDelegate 拒绝为实例方法创建委托(delegate)

c# - 消息在再次可见之前会在 Azure 队列中隐藏多长时间?

c# - 序列化实现 INotifyPropertyChanged 的​​类的实例时出现 SerializationException

c# - 在定义后立即执行 lambda 表达式?

c# - 如何避免或检测 C# 中的隐式委托(delegate)推断?

javascript - 使用类选择器附加事件处理程序是否会影响该类的动态添加元素?