Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果有其他扩展_C#_Extension Methods - Fatal编程技术网

C# 如果有其他扩展

C# 如果有其他扩展,c#,extension-methods,C#,Extension Methods,如果需要对对象执行条件操作,我喜欢使用此扩展: T IfTrue<T>(this T source, Func<T, bool> shouldPerform, Action<T> action) { if (shouldPerform(source)) { action(source); } return source; } 但我最终还是用在了 someObject.IfTrue(self=>ValidateObjec

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

T IfTrue<T>(this T source, Func<T, bool> shouldPerform, Action<T> action) {
    if (shouldPerform(source)) {
        action(source);
    }
    return source;
}
但我最终还是用在了

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

并且没有附加的
Else
扩展名


因此,我的问题是:是否可以将其分成两个独立的扩展(注意:两个扩展仍应返回
T
)?

您可以让
IfTrue
返回一个新类,该类包含
对象的属性,条件是否为真,以及
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);
    }
}
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 };
}

正如大多数评论所说,用两个独立的
If
Else
部分构建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;
}
[DebuggerStepThrough]
内部静态T If(此T源,函数为真,操作为thenAction,操作为elseAction=null){
如果(isTrue(来源)){
行动(来源);
}否则{
elseAction?.Invoke(源);
}
返回源;
}

此扩展既可以执行
then
操作,也可以执行
else
操作,如果需要,仍然可以只执行
then

为什么要使用此扩展而不是
if/else
语句
source
已经在范围内,因此您不需要返回它。问题是iftrue的链接表明该链根据结果有不同的内容(如linq
where
),在这种情况下它没有。这看起来就像是花哨的代码综合症如果你只想在方法调用之间传播This,你不妨编写一个更通用的T Tap(This T,Action act)方法,并将if/else逻辑嵌入其中。这感觉像是一个扩展方法太远了@DovydasSopa,但是通过链接这些方法,您不会得到任何好处。只要不链接这些方法,你的代码就会有很大的改进。没错,但是如果我不需要其他部分,我需要编写额外的操作:
someObject.IfTrue(…).Source
好了,现在我明白你想做什么了。但是您必须将shouldPerform的结果存储在某个地方。。。
[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;
}