2016-02-25 17 views
0

我喜歡使用這個擴展,如果我需要一個對象執行條件動作:的if-else擴展

T IfTrue<T>(this T source, Func<T, bool> shouldPerform, Action<T> action) { 
    if (shouldPerform(source)) { 
     action(source); 
    } 
    return source; 
} 

但我想知道什麼是最好的解決辦法,如果我需要兩個trueelse行動?我形象的使用應該是這樣的:

someObject.IfTrue(self => ValidateObject(self), self => self.TrueAction()).Else(self => self.FalseAction());

一個我認爲是增加額外的參數IfTrue方法的可能性:

T IfTrue<T>(this T source, Func<T, bool> shouldPerform, Action<T> trueAction, Action<T> falseAction = null) { 
    if (shouldPerform(source)) { 
     trueAction(souce); 
    } else if (falseAction != null) { 
     falseAction(source); 
    } 
    return source; 
} 

但後來我結束了

使用它someObject.IfTrue(self => ValidateObject(self), self => self.TrueAction(), self => self.FalseAction());

和不具有附加Elseè具有它xtension。

所以,我的問題:可以這樣拆分爲兩個獨立的擴展名(注:兩個擴展還是應該回到T)?

+5

你爲什麼要用這個而不是'if/else'語句? 'source'已經在範圍之內,所以你不需要返回它。 – Lee

+0

@如果我需要用其他方法鏈接,我使用我的IfTrue擴展。然後返回它可以在之後添加另一種方法。 –

+1

問題在於iftrue的鏈接表明鏈根據結果具有不同的事物(如linq'where),在這種情況下它不是。這看起來就像花式代碼證 – pm100

回答

0

由於大部分評論說 - 有沒有簡單的方法,如果,真否則extenstion有兩個獨立IfElse部件,所以我最終使這之一:

[DebuggerStepThrough] 
internal static T If<T> (this T source, Func<T, bool> isTrue, Action<T> thenAction, Action<T> elseAction = null) { 
    if (isTrue (source)) { 
     thenAction (source); 
    } else { 
     elseAction?.Invoke (source); 
    } 
    return source; 
} 

這個擴展可以採取兩種thenelse行動,並仍然能夠只是還需要是否只then

0

你可以有IfTrue返回與屬性的新類的source對象和天氣條件爲真,且Else方法,這樣

class Conditional<T> // or however you want to call it 
{ 
    public T Source { get; set; } // the initial source object 
    public bool Result { get; set; } // weather the IfTrue method called the action 

    public void Else(Action<T> action) 
    { 
     if (!Result) 
      action(Source); 
    } 
} 

,改變IfTrue是這樣

Conditional<T> IfTrue<T>(this T source, Func<T, bool> shouldPerform, Action<T> action) { 
    if (shouldPerform(source)) { 
     action(source); 
     return new Conditional<T> { Source = source, Result = true }; 
    } 
    return new Conditional<T> { Source = source, Result = false }; 
} 
+0

沒錯,但這時如果我**不會**需要別人的一部分,我需要編寫額外的操作:'someObject.IfTrue(...)Source' –

+0

好吧,現在我明白你想什麼做。但是你將不得不將結果保存在'shouldPerform'的某個地方...... – squill25