的if-else扩展
我喜欢使用这个扩展,如果我需要一个对象执行条件动作:的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
)?
由于大部分评论说 - 有没有简单的方法,如果,真否则extenstion有两个独立If
和Else
部件,所以我最终使这之一:
[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;
}
这个扩展可以采取两种then
和else
行动,并仍然能够只是还需要是否只then
。
你可以有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 };
}
没错,但这时如果我**不会**需要别人的一部分,我需要编写额外的操作:'someObject.IfTrue(...)Source' –
好吧,现在我明白你想什么做。但是你将不得不将结果保存在'shouldPerform'的某个地方...... – squill25
你为什么要用这个而不是'if/else'语句? 'source'已经在范围之内,所以你不需要返回它。 – Lee
@如果我需要用其他方法链接,我使用我的IfTrue扩展。然后返回它可以在之后添加另一种方法。 –
问题在于iftrue的链接表明链根据结果具有不同的事物(如linq'where),在这种情况下它不是。这看起来就像花式代码证 – pm100