如何链接接受Func <>委托的方法重载?(C#)

Tim*_*ter 1 c# generics delegates predicate

我有一个带有两个重载的方法,如下所示:

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

    return condition.Invoke();
}

bool Evaluate<T>(Func<T, bool> condition, T value)
{
    // Same logic as the first method overload

    return condition.Invoke(value);
}
Run Code Online (Sandbox Code Playgroud)

由于两个方法重载都包含大致相同的逻辑,我希望将它们链接在一起,但我看不到如何做到这一点.我想第一个方法overoad需要构造一个委托,它传递给第二个重载,但是不清楚这个委托应采取什么形式.

非常感谢你的建议,

蒂姆

Jor*_*dão 6

试试这个(你不需要打电话Invoke):

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

bool Evaluate<T>(Func<T, bool> condition, T value) {
  return Evaluate(() => condition(value));
} 
Run Code Online (Sandbox Code Playgroud)

或者也许你的逻辑是可重用的,用它自己的方法提取它可能是有意义的:

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

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

void Logic() {
  // logic...
} 
Run Code Online (Sandbox Code Playgroud)