8

我希望能够写一些东西

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) {
}

每当谓词评估为真或假时,如何检查我的 Start 函数?我对谓词的使用正确吗?

谢谢

4

3 回答 3

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);
于 2010-04-24T03:56:52.777 回答
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);
于 2010-04-24T04:02:05.467 回答
1

从设计的角度来看,将谓词传递给函数的目的通常是过滤某些 IEnumerable,针对每个元素测试谓词以确定该项是否是过滤集的成员。

您最好在示例中简单地使用具有布尔返回类型的函数。

于 2010-04-24T04:03:10.543 回答