ArgumentException的主场迎战ArgumentNullException? [英] ArgumentException vs. ArgumentNullException?
问题描述
我重构一些代码,添加一个方法,该方法将取代(即将成为)的方法已过时。该方法具有以下签名:
I’m refactoring some code and adding a method which will replace a (soon-to-be) deprecated method. The new method has the following signature:
FooResult Foo(FooArgs args) { ... }
弃用的方法包含的参数越来越多。这些参数现在对 FooArgs
类属性。该方法已过时具有检查空值与以下几种结构的约束条件:
The deprecated method contained a growing list of parameters. These parameters are now properties on the FooArgs
class. The deprecated method has several guard conditions which checked for null values with the following structure:
if (parameter1 == null)
throw new ArgumentNullException("parameter1");
if (parameter... == null)
throw new ArgumentNullException("parameter...");
if (parameterN == null)
throw new ArgumentNullException("parameterN");
现在,该参数已经坍塌成 FooArgs
类,我应该抛出 ArgumentNullException 为 FooArgs
参数的各个属性:
Now that the parameters have been collapsed into the FooArgs
class should I throw an ArgumentNullException for the individual properties of the FooArgs
parameter:
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");
或者抛出一个更一般的的ArgumentException 的整个 FooArgs
参数:
Or to throw a more general ArgumentException for the entire FooArgs
parameter:
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");
谢谢!
Thanks!
推荐答案
您需要添加一个检查为ARGS本身非空。该ANE不适合单个组件,所以你需要使用更一般的AE,是这样的:
You need to add a check for the args itself to be non-null. The ANE is not appropriate for individual components, so you need to use more general AE, like this:
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");
这篇关于ArgumentException的主场迎战ArgumentNullException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!