If-else 扩展

If-else extension

如果我需要对对象执行条件操作,我喜欢使用此扩展程序:

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 扩展。

那么,我的问题是:这是否可以拆分为两个单独的扩展(注意:两个扩展应该仍然 return T)?

您可以 IfTrue return 一个新的 class 具有 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 };
}

正如大多数评论所说 - 没有简单的方法可以用两个单独的 IfElse 部分构建 If-True-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;
}

此扩展程序可以执行 thenelse 操作,并且如果需要仍然可以只执行 then