为什么resharper提出以下建议?

时间:2009-02-26 19:25:11

标签: c# resharper

我的代码是......

public static void AssertNotNull<T>(string name, T val) {
    if (val == null)
        throw new ArgumentNullException(String.Format("{0} must not be null", name));
}

Resharper推荐......

public static void AssertNotNull<T>(string name, T val) {
    if (Equals(val, default(T)))
        throw new ArgumentNullException(String.Format("{0} must not be null", name));
}

6 个答案:

答案 0 :(得分:13)

因为它不知道T是值类型还是引用类型,所以它使代码适用于这两种类型。

答案 1 :(得分:12)

我是Berado的第二个回答,但是会补充一点,你可以通过添加下面的约束来防止这种情况:

public static void AssertNotNull<T>(string name, T val) where T : class

答案 2 :(得分:2)

这显然不是在这个实例中你想要的东西,但它只是试图提供帮助,通过忘记引用类型可用于{确保你没有引入错误{1}}。与@Michael Meadows一样,您可能希望将T约束添加到class

答案 3 :(得分:1)

这两种方法并不相同。第一个允许AssertNotNull(“foo”,0),而第二个抛出。我认为Resharper在这种情况下过于热心。

答案 4 :(得分:0)

我想因为T可能是非引用类型。

答案 5 :(得分:0)

如果您知道T将永远是一个类,那么添加一个where子句来表示,那么您的原始代码就可以了。

public static void AssertNotNull<T>(string name, T val)
    where T : class
    {
        if (val == null)
            throw new ArgumentNullException(String.Format("{0} must not be null", name));
    }