开发者

How to define a predicate as a function argument

开发者 https://www.devze.com 2022-12-27 19:53 出处:网络
I want to be able to write something as void Start(some condition that might evaluate to either true or false) {

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?

开发者_如何学JAVA

Thanks


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消