正在重构一些代码:
FooResult Foo(FooArgs args) { ... }
使用以下结构检查空值:
if (parameter1 == null)
throw new ArgumentNullException(“parameter1”);
if (parameter... == null)
throw new ArgumentNullException(“parameter...”);
if (parameterN == null)
throw new ArgumentNullException(“parameterN”);
ArgumentNullException属性数:
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”);
或者ArgumentExceptionFooArgs
参数:
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”);
可以考虑将验证FooArgs
转移到FooArgs
类本身。如果这个类是专门为移动参数而设计的,那么它可能是无效的,在这种情况下,可以允许它的构造函数进行验证。
需要添加一个检查,以确保args本身是非空的
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”);