NullReferenceException

NullReferenceException

本文介绍了C#:验证“这个”的最佳做法扩展方法的论证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个扩展方法

  public static T TakeRandom< T>(this IEnumerable< T> e)
{
...

要验证参数e,我应该: / b

A)if(e == null)throw new NullReferenceException()

B)if(e == null)throw new ArgumentNullException( e)

C)不检查e



有什么共识?



我的第一个想法是总是验证参数,所以抛出一个ArgumentNullException。再次,由于TakeRandom()成为e的一个方法,也许应该是一个NullReferenceException。但是如果是NullReferenceException,如果我尝试使用TakeRandom()中的e的成员,NullReferenceException将被抛出。



也许我应该使用反射器高峰,找出

解决方案

你应该抛出一个ArgumentNullException。您正在尝试进行参数验证,因此应该将异常调整为参数验证。 NullReferenceException不是参数验证异常。这是一个运行时错误。不要忘记,扩展方法只是静态方法,可以这样调用。虽然在扩展方法上抛出一个NullReferenceException对于表面看起来似乎是有意义的,但是静态方法这样做是没有意义的。在方法中无法确定调用约定,因此ArgumentException是更好的选择。



此外,您不应该显式抛出NullReferenceException。这只应该由CLR抛出。当显式抛出通常仅由CLR抛出的异常时,会发生微妙的差异。



这也接近以下的一个重复的






Let's say I have an extension method

public static T TakeRandom<T>(this IEnumerable<T> e)
{
    ...

To validate the argument e, should I:

A) if (e == null) throw new NullReferenceException()
B) if (e == null) throw new ArgumentNullException("e")
C) Not check e

What's the consensus?

My first thought is to always validate arguments, so thrown an ArgumentNullException. Then again, since TakeRandom() becomes a method of e, perhaps it should be a NullReferenceException. But if it's a NullReferenceException, if I try to use a member of e inside TakeRandom(), NullReferenceException will be thrown anyway.

Maybe I should peak using Reflector and find out what the framework does.

解决方案

You should throw an ArgumentNullException. You're attempting to do argument validation and hence should throw an exception tuned to argument validation. NullReferenceException is not an argument validation exception. It's a runtime error.

Don't forget, extension methods are just static methods under the hood and can be called as such. While it may seem on the surface to make sense to throw a NullReferenceException on an extension method, it does not make sense to do so for a static method. It's not possible to determine the calling convention in the method and thus ArgumentException is the better choice.

Also, you should not ever explicitly throw a NullReferenceException. This should only be thrown by the CLR. There are subtle differences that occur when explicitly throwing exceptions that are normally only thrown by the CLR.

This is also close to a dupe of the following

这篇关于C#:验证“这个”的最佳做法扩展方法的论证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:09