编程语言
首页 > 编程语言> > C#-谓词的委托不起作用

C#-谓词的委托不起作用

作者:互联网

我倾向于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>

同样的事情是

还有另一种方式.您可以创建新的谓词.

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

标签:delegates,c,lambda
来源: https://codeday.me/bug/20191119/2037232.html