1

我正在尝试执行以下操作:

MyObject.If(x => x.ID == 10, new MyAction("ID10")).If(x => x.Value < 20, new MyAction("Value20")).DoSomethingWithMyAction();

MyObject 是一个具有一些我需要检查的属性的对象...

DoSomethingWithMyAction() 是一个 MyAction 扩展,它对第一个失败条件的 MyAction 执行某些操作。

如果可能是这样的:

public static If<T>(this T myobject, Func<T, Boolean> predicate, MyAction action) where T : MyObject {

  if (predicate(myobject)
    // Return ??? >> Move to Next If
  else
    // Return action

} // If

那么 DoSomethingWithMyAction() 将只是一个 MyAction 扩展。

我的问题是: 1 - 如何链接 IF;2 - 如何使 DoSomethingWithMyAction() 使用第一个 IF 的 MyAction 失败。

谢谢你,米格尔

4

1 回答 1

2

编辑:我误解了你的问题,现在没有时间重新审视我的代码。但它这样的:

您可能需要构造某种表示链本身的类型。就像是:

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返回“失败的谓词中的值”或类似的东西......无论如何,这是一般要点。

于 2012-07-20T17:58:43.203 回答