首页 / C# / C#-谓词的委托不起作用
C#-谓词的委托不起作用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#-谓词的委托不起作用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1668字,纯文字阅读大概需要3分钟。
内容图文
![C#-谓词的委托不起作用](/upload/InfoBanner/zyjiaocheng/663/39d7899d9b344f3c8a6b880eeb97fc8a.jpg)
我倾向于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));
内容总结
以上是互联网集市为您收集整理的C#-谓词的委托不起作用全部内容,希望文章能够帮你解决C#-谓词的委托不起作用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。