How to define a predicate as a function argument

谁说胖子不能爱 提交于 2019-12-09 16:39:14

问题


I want to be able to write something as

void Start(some condition that might evaluate to either true or false) {
    //function will only really start if the predicate evaluates to true
}

I'd guess it must be something of the form:

void Start(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?

Thanks


回答1:


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);



回答2:


You could do something like this:

void Start(Predicate<int> predicate, int value)
    {
        if (predicate(value))
        {
            //do Something
        }         
    }

Where you call the method like this:

Start(x => x == 5, 5);

I don't know how useful that will be. Predicates are really handy for things like filtering lists:

List<int> l = new List<int>() { 1, 5, 10, 20 };
var l2 = l.FindAll(x => x > 5);



回答3:


From a design perspective, the purpose of a predicate being passed into a function is usually to filter some IEnumerable, the predicate being tested against each element to determine whether the item is a member of the filtered set.

You're better off simply having a function with a boolean return type in your example.



来源:https://stackoverflow.com/questions/2703143/how-to-define-a-predicate-as-a-function-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!