2012-07-20 20 views
1

我努力做到以下幾點:連鎖IF條件並執行第一個條件。在C#

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 - 如何鏈接中頻; 2 - 如何使DoSomethingWithMyAction()使用第一個IF的MyAction失敗。

謝謝你, 米格爾

+1

在所有應有的尊重,你試圖做的不是慣用的,它是無法維護的。 if/else塊將比這更容易維護。 – 48klocs 2012-07-20 18:00:53

回答

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回報「值從失敗的謂詞「或類似的東西...無論如何,這是一般的要點。