我希望能够写出一些东西
void Start(some condition that might evaluate to either true or false) {
//function will only really start if the predicate evaluates to true
}
我猜它必须是这样的形式:
void Start(Predicate predicate) {
}
如果谓词评估为true或false,我如何检查Start函数内部?我对谓词的使用是否正确?
由于
答案 0 :(得分:13)
这是在函数中使用谓词的一个简单示例。
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);
答案 1 :(得分:2)
你可以这样做:
void Start(Predicate<int> predicate, int value)
{
if (predicate(value))
{
//do Something
}
}
你在这里调用这样的方法:
Start(x => x == 5, 5);
我不知道会有多大用处。 Predicates
对于过滤列表等内容非常方便:
List<int> l = new List<int>() { 1, 5, 10, 20 };
var l2 = l.FindAll(x => x > 5);
答案 2 :(得分:1)
从设计角度来看,传递给函数的谓词的目的通常是过滤一些IEnumerable,对每个元素进行测试的谓词,以确定该项是否是过滤集的成员。
你最好只是在你的例子中使用一个带布尔返回类型的函数。