链IF条件并执行第一个。在C#中

时间:2012-07-20 17:42:25

标签: c# if-statement chain

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

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失败。

谢谢你, 米格尔

1 个答案:

答案 0 :(得分: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>更改为MyAction,并使Execute返回“失败的谓词中的值”或类似的内容......无论如何,这是一般的要点。