ArgumentException与ArgumentNullException?

Joh*_*oon 21 .net c#

我正在重构一些代码并添加一个方法来替换(即将推出)已弃用的方法.新方法具有以下特征:

FooResult Foo(FooArgs args) { ... }
Run Code Online (Sandbox Code Playgroud)

不推荐使用的方法包含越来越多的参数.这些参数现在是FooArgs类的属性.不推荐使用的方法有几个保护条件,它使用以下结构检查空值:

if (parameter1 == null)
    throw new ArgumentNullException(“parameter1”);
if (parameter... == null)
    throw new ArgumentNullException(“parameter...”);
if (parameterN == null)
    throw new ArgumentNullException(“parameterN”);
Run Code Online (Sandbox Code Playgroud)

既然已将参数折叠到FooArgs类中,我应该为参数的各个属性抛出ArgumentNullExceptionFooArgs:

if (args.Property1 == null)
    throw new ArgumentNullException(“args.Property1”);
if (args.Property... == null)
    throw new ArgumentNullException(“args.Property...”);
if (args.PropertyN == null)
    throw new ArgumentNullException(“args.PropertyN”);
Run Code Online (Sandbox Code Playgroud)

或者为整个参数抛出更一般的ArgumentException: FooArgs

if (args.Property1 == null)
    throw new ArgumentException(“Property1 cannot be null.”, “args”);
if (args.Property... == null)
    throw new ArgumentException(“Property... cannot be null.”, “args”);
if (args.PropertyN == null)
    throw new ArgumentException(“Property2 cannot be null.”, “args”);
Run Code Online (Sandbox Code Playgroud)

谢谢!

das*_*ght 26

您需要将args本身的检查添加为非null.ANE不适合单个组件,因此您需要使用更通用的AE,如下所示:

if (args == null)
    throw new ArgumentNullException(“args”);
if (args.Property1 == null)
    throw new ArgumentException(“Property1 cannot be null.”, “args”);
if (args.Property... == null)
    throw new ArgumentException(“Property... cannot be null.”, “args”);
if (args.PropertyN == null)
    throw new ArgumentException(“Property2 cannot be null.”, “args”);
Run Code Online (Sandbox Code Playgroud)

  • @Slade这是完全正确的:如果`args`为null,则抛出ANE; 如果`args`不为null,但其中一个组件为null(这当然使`args`无效)抛出更一般的AE. (4认同)

Ree*_*sey 10

虽然我完全同意dasblinkenlight的回答,但您可能还需要考虑将验证FooArgs转移到FooArgs类本身.如果这个类专门设计用于移动参数,那么它可能无效,因为它具有null proeprties,在这种情况下,我会允许它的构造函数进行验证.