用于整数的ArgumentNullException

时间:2020-03-05 18:40:49  来源:igfitidea点击:

在.NET中,如果值是Integer.MinValue或者Integer = 0(假设0不是有效值),则为Integer抛出参数null异常是否更合适?

解决方案

回答

好吧,我想如果我们使用的是int,那么最好说InvalidArgumentException。

或者,我们可以通过将INT声明为int来使它们成为可空的? (特别是如果我们希望int为空值。)

回答

除非参数实际上为null,否则抛出ArgumentNullException是不合适的。而是抛出ArgumentOutOfRangeException(最好是一条消息,通知用户实际上可以接受int的哪些值)。

ArgumentOutOfRangeException is thrown when a method is invoked and at least one of the arguments passed to the method is not a null reference (Nothing in Visual Basic) and does not contain a valid value.

回答

如果参数不为null,则不要抛出ArgumentNullException。抛出一个" ArgumentException"可能更合理,在这里解释。

编辑:ArgumentOutOfRangeException可能更好,如以上由Avenger546建议的那样。