访问参数的属性时使用ArgumentNullException

Ant*_*t P 1 c# exception-handling exception conventions

假设我有一个Foo具有复杂属性的类Bar.然后,假设我在其他类中有类似以下的方法:

public void DoSomething(Foo foo)
{
    if (foo == null)
        throw new ArgumentNullException("foo");
    if (foo.Bar == null)
        throw new ArgumentNullException("bar");
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下使用是否ArgumentNullException适当,严格来说,foo.Bar在这种情况下不是一个论据?我已经阅读并且可以理解,NullReferenceException手动抛出是不合适的.这告诉我我需要抽象吗?

public void DoSomething(Foo foo)
{
    if (foo == null)
        throw new ArgumentNullException("foo");
    DoSomethingElse(foo.Bar);
}

private void DoSomethingElse(Bar bar)
{
    if (bar == null)
        throw new ArgumentNullException("bar");
}
Run Code Online (Sandbox Code Playgroud)

我的第一个代码片段是"正确"用法ArgumentNullException吗?处理这种情况的传统方法是什么?

谢谢.

Lee*_*Lee 10

理想情况下,Foo该类将确保其Bar属性永远不为null.如果那是不可能的,我会ArgumentException在这种情况下抛出一个,因为参数不是null,但是它是无效的.