How to define a predicate as a function argument

2020-07-09 08:52发布

问题:

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.