开发者

Passing a bool condition to method which I can invoke when I need

开发者 https://www.devze.com 2022-12-23 03:26 出处:网络
I need to pass in a predicate which I can invoke whenever I want (just like a delegate). I am trying to do something like this (I thought Predicate delegate would meet my needs):

I need to pass in a predicate which I can invoke whenever I want (just like a delegate). I am trying to do something like this (I thought Predicate delegate would meet my needs):

MyMethod(Predic开发者_如何学JAVAate,string> pred);

Called like: MyMethod(s => s.Length > 5);

I want to write the condition inline BUT invoke it when I want, just like a delegate. How could I do this>?

Thanks


You would do it exactly like you wrote:

void MyMethod(Func<string, bool> method)  // Could be Predicate<string> instead
{
    // Do something
    // ...
    // Later, if you choose to invoke your method:

    if( method(theString) )
    {
      //...
    }
}


Like the following

bool MyMethod(Predicate<string> pred) {
  ...
  if ( pred("foo") ) { ... 
  }
}

Then

MyMethod(s => s.Length > 5);
0

精彩评论

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

关注公众号