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