5

Let's say I have a method:

public void SayHello(User user)
{
    if (user == null)
        throw new ArgumentNullException("user");

    Console.Write(string.Format("Hello from {0}", user.Name));
}

It's clear that I should use ArgumentNullException as it shown above to validate that user is not null. Now how can I validate that user.Name is not empty? Would it be a good practice to do like that:

if (string.IsNullOrWhiteSpace(user.Name))
    throw new ArgumentNullException("user", "Username is empty");
4

2 回答 2

9

不,您不应该为此目的抛出ArgumentNullException,因为它是专门为解决null引用而设计的。

将空引用(Visual Basic 中的 Nothing)传递给不接受它作为有效参数的方法时引发的异常。

相反,您应该使用ArgumentException或您自己的子类。让我们说InvalidUserException或类似的东西。

甚至 msdn 都在谈论.

ArgumentNullException 的行为与 ArgumentException 相同。提供它以便应用程序代码可以区分由空参数引起的异常和由非空参数引起的异常。对于由非空参数引起的错误

所以很明显,如果参数是null使用ArgumentNullExceptionArgumentException否则。

也就是说,理想情况下,您甚至不应该允许某人User使用无效用户名创建实例。我真的会User以永远不会包含Nameas的方式设计我的课程null

于 2014-12-29T13:32:42.050 回答
4

ArgumentException如果参数为空,你应该抛出,ArgumentNullException应该只用于空参数:

if (string.IsNullOrWhiteSpace(user.Name))
    throw new ArgumentException("Username is empty", "user");
于 2014-12-29T13:32:01.363 回答