人们在管理类(class)的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 ....
}

在我目前正在研究的项目中,有许多类在公共(public)方法上有一组类似的保护子句。

我知道.NET 4.0代码契约(Contract),但是目前这不是我们团队的选择。

最佳答案

我见过的许多项目都使用静态Guard类。

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

在我看来,它使代码更整洁。
Guard.ArgumentIsNotNull(arg1, "arg1");

关于c# - 重构 guard 条款,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1597884/

10-13 03:12