开发者

How to chain method overloads that accept Func<> delegates ? (C#)

开发者 https://www.devze.com 2023-01-21 17:39 出处:网络
I have a method with two overloads, as follows: bool Evaluate(Func<bool> condition) { // Some logic

I have a method with two overloads, as follows:

bool Evaluate(Func<bool> condition)
{
    // Some logic

    return condition.Invoke();
}

bool Evaluate<T>(Func<T, bool> condition, T value)
{
    // Sam开发者_如何学Ce logic as the first method overload

    return condition.Invoke(value);
}

Since both method overloads contain largely identical logic, I wish to chain them together, but I can't see how to do this. I imagine the first method overoad needs to construct a delegate that it passes to the second overload, but it's not clear what form this delegate should take.

Many thanks for your advice,

Tim


Try this (you don't need to call Invoke):

bool Evaluate(Func<bool> condition) {
  // logic ...
  return condition();
}

bool Evaluate<T>(Func<T, bool> condition, T value) {
  return Evaluate(() => condition(value));
} 

Or maybe your logic is reusable, it might make sense to extract it in its own method:

bool Evaluate(Func<bool> condition) {
  Logic();
  return condition();
}

bool Evaluate<T>(Func<T, bool> condition, T value) {
  Logic();
  return condition(value);
}

void Logic() {
  // logic...
} 


Something like this:

bool Evaluate(Func<bool> condition)
{
    return Evaluate(p => condition.Invoke(), false);
}


The easiest way is to wrap the original no parameter delegate with one that accepts and ignores a single parameter.

bool Evaluate(Func<bool> condition) 
{ 
    return Evaluate( _ => condition(), 0); 
} 


Your first overload cannot call the second unless you are going to "make up" a value to pass. Your second can easily call the first, though.

bool Evaluate<T>(Func<T, bool> condition, T value)
{
   return Evaluate( () => condition(value));
}
0

精彩评论

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