重构保护条款

Kan*_*ane 29 c# validation guard-clause

人们采用什么方法(如果有的话)管理班级中的防护条款爆炸?例如:

public void SomeMethod<T>(string var1, IEnumerable<T> items, int count)
{
    if (string.IsNullOrEmpty(var1))
    {
        throw new ArgumentNullException("var1");
    }

    if (items == null)
    {
        throw new ArgumentNullException("items");
    }

    if (count < 1)
    {
        throw new ArgumentOutOfRangeException("count");
    }

    ... etc ....
}
Run Code Online (Sandbox Code Playgroud)

在我目前正在进行的项目中,有许多类在公共方法上具有类似的一组保护条款.

我知道.NET 4.0代码合同,但目前这不是我们团队的选择.

Dav*_*own 49

我见过很多项目都使用静态Guard类.

public static class Guard {
    public static void ArgumentIsNotNull(object value, string argument) {
        if (value == null)
            throw new ArgumentNullException(argument);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我看来,它使代码更清晰.

Guard.ArgumentIsNotNull(arg1, "arg1");
Run Code Online (Sandbox Code Playgroud)

  • 我建议你使用`[DebuggerHiddenAttribute]`来注释guard方法.这可确保调试器不会在这些方法中停止,而是返回到原始方法.请参阅http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerhiddenattribute.aspx如果您使用的是ReSharper,还可以使用`[ContractAnnotationAttribute]`和`argument`参数来注释保护方法可以使用`[InvokerParameterName]`注释,为您提供参数名称字符串的智能感知. (15认同)
  • 我只是发布了同样的东西。唯一的问题是它把这个方法放在堆栈跟踪的顶部,而不是将原始方法放在顶部,而不是它有那么大。这种模式显然可用于不同类型以检查一系列值等...... (2认同)