我喜歡使用這個擴展,如果我需要一個對象執行條件動作:的if-else擴展
T IfTrue<T>(this T source, Func<T, bool> shouldPerform, Action<T> action) {
if (shouldPerform(source)) {
action(source);
}
return source;
}
但我想知道什麼是最好的解決辦法,如果我需要兩個true
和else
行動?我形象的使用應該是這樣的:
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
)?
你爲什麼要用這個而不是'if/else'語句? 'source'已經在範圍之內,所以你不需要返回它。 – Lee
@如果我需要用其他方法鏈接,我使用我的IfTrue擴展。然後返回它可以在之後添加另一種方法。 –
問題在於iftrue的鏈接表明鏈根據結果具有不同的事物(如linq'where),在這種情況下它不是。這看起來就像花式代碼證 – pm100