编辑:我误解了你的问题,现在没有时间重新审视我的代码。但它是这样的:
您可能需要构造某种表示链本身的类型。就像是:
public class ChainedExecution<T>
{
private readonly T target;
private readonly ChainedExecution<T> previous;
private readonly Func<T, bool> predicate;
private readonly Action<T> action;
private ChainedExecution(T target, ChainedExecution<T> previous,
Func<T, bool> predicate, Action<T> action)
{
this.target = target;
this.previous = previous;
this.predicate = predicate;
this.action = action;
}
public ChainedExecution<T> Or(Func<T, bool> newPredicate, Action<T> newAction)
{
return new ChainedExecution<T>(target, this, newPredicate, newAction);
}
public bool Execute()
{
if (previous != null && previous.Execute())
{
// An earlier action has handled it.
return true;
}
if (predicate(target))
{
action(target);
return true;
}
return false;
}
public static ChainedExecution<T> Start(T target, Func<T, bool> predicate,
Action<T> action)
{
return new ChainedExecution<T>(target, null, predicate, action);
}
}
然后:
public static class ChainedExecution
{
public static ChainedExecution<T> If<T>(this T target,
Func<T, bool> predicate,
Action<T> action)
{
return ChainedExecution<T>.Start(target, predicate, action);
}
}
并将其用作:
foo.If(x => x.Value < 20, x => Console.WriteLine("Bang! Too low"))
.Or(x => x.Name == null, x => Console.WriteLine("Null name"))
.Execute();
您需要将 更改Action<T>
为 a MyAction
,并Execute
返回“失败的谓词中的值”或类似的东西......无论如何,这是一般要点。