如何定义predicate作为函数参数 [英] How to define a predicate as a function argument
本文介绍了如何定义predicate作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够写的东西为
void Start(some condition that might evaluate to either true or false) {
//function will only really start if the predicate evaluates to true
}
我猜一定是什么形式的:</ P>
I'd guess it must be something of the form:
void Start(Predicate predicate) {
}
我如何检查在我开始功能只要predicate评估为真或假?是我使用了predicate是否正确?
How can I check inside my Start function whenever the predicate evaluated to true or false? Is my use of a predicate correct?
感谢
推荐答案
下面是一个函数使用predicate的一个简单的例子。
Here's a trivial example of using a predicate in a function.
static void CheckRandomValueAgainstCriteria(Predicate<int> predicate, int maxValue)
{
Random random = new Random();
int value = random.Next(0, maxValue);
Console.WriteLine(value);
if (predicate(value))
{
Console.WriteLine("The random value met your criteria.");
}
else
{
Console.WriteLine("The random value did not meet your criteria.");
}
}
...
CheckRandomValueAgainstCriteria(i => i < 20, 40);
这篇关于如何定义predicate作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文