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>...とにかく、それが一般的な要点ですMyActionExecute

于 2012-07-20T17:58:43.203 に答える