C# 通过反转函数扩展方法<;T、 布尔>;

C# 通过反转函数扩展方法<;T、 布尔>;,c#,extension-methods,func,C#,Extension Methods,Func,我编写了一个扩展方法,如果给定类型T的布尔函数的计算结果为true/false,则会引发异常 public static void ThrowIf<T>(this T source, Func<T,bool> func, string name, bool invert = false) { if (func.Invoke(source) != invert) throw new ArgumentException(

我编写了一个扩展方法,如果给定类型T的布尔函数的计算结果为true/false,则会引发异常

    public static void ThrowIf<T>(this T source, Func<T,bool> func, string name, bool invert = false)
    {
        if (func.Invoke(source) != invert)
            throw new ArgumentException(func.Method.Name + " check failed, inverted:" + invert, name);
    }

是否有比在我的ThrowIf中传递标志或创建ThrowIfNot更简洁的解决方案来包含反转功能?

我相信显然另一种方法更有意义(正如您在问题中所说的…):

…您可以将
ThrowIf
与invert
true
/
false
参数设置为私有:

private static void ThrowIf(此T源代码,Func Func,字符串名,bool invert)
{
if(函数调用(源)!=invert)
抛出新ArgumentException(func.Method.Name+“检查失败,反转:”+invert,Name);
}
公共静态void ThrowIf(此T源,Func Func,字符串名)
=>ThrowIf(源、函数、名称、假);
公共静态void ThrowIfNot(此T源,Func Func,字符串名)
=>ThrowIf(源、函数、名称、真);
顺便说一句,如果要实现参数验证,最好重构所有要使用的东西:

public void SomeMethod(string someParameter)
{
    Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(someParameter));
}
public void SomeMethod(字符串someParameter)
{
Contract.Requires(!string.IsNullOrEmpty(someParameter));
}

如果您没有传递一些应该反转的信息,并且您没有其他名称来表示该行为,这应该如何工作?适用于所有类型的扩展方法?讨厌。当输入为
null
时,是否引发
ArgumentException
而不是
ArgumentNullException
?讨厌。检查
File.Exists
而不是仅仅打开,引入竞争条件?讨厌。不仅要仔细考虑如何改进此方法,还要仔细考虑是否需要此方法。@hvd是的,正确的观点,我只是发布了一些简单的示例。实际上我并不是这样使用它们的。@poke类似的东西,例如name.ThrowIf(s=>!String.IsNullOrWhiteSpace(s),“name”);我想这对我来说已经够干净了如果你同意的话,那这不是已经行了吗?你有什么问题吗?谢谢你的代码合同提示。我忘了。
name.ThrowIf(String.IsNullOrEmpty, "name");
path.ThrowIfNot(File.Exists, "path");
private static void ThrowIf<T>(this T source, Func<T,bool> func, string name, bool invert)
{
    if (func.Invoke(source) != invert)
        throw new ArgumentException(func.Method.Name + " check failed, inverted:" + invert, name);
}

public static void ThrowIf<T>(this T source, Func<T, bool> func, string name) 
       => ThrowIf<T>(source, func, name, false);
public static void ThrowIfNot<T>(this T source, Func<T, bool> func, string name) 
       => ThrowIf<T>(source, func, name, true);
public void SomeMethod(string someParameter)
{
    Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(someParameter));
}