NullReferenceException

NullReferenceException

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

问题描述

让我们说我有一个扩展方法

Let's say I have an extension method

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

要验证参数E,我应该:

To validate the argument e, should I:

A)如果(E == NULL)抛出新的NullReferenceException()

b)如果(E == NULL)抛出新的ArgumentNullException( E)

C)未查收

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

有什么共识?

我首先想到的是要始终验证参数,所以抛出ArgumentNullException。话又说回来,既然TakeRandom()成为电子商务的方法,也许它应该是一个NullReferenceException。但如果它是一个NullReferenceException,如果我尝试使用内TakeRandom()E的成员,NullReferenceException异常无论如何都会被抛出。

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.

推荐答案

您应该抛出一个ArgumentNullException。你试图做参数验证,因此应该抛出调谐参数验证异常。 NullReferenceException异常不是一个参数验证例外。这是一个运行时错误。

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.

不要忘了,扩展方法是引擎盖下只是静态方法,可以称为这样的。虽然它可能表面上看起来有道理扔在一个扩展方法一个NullReferenceException,这没有任何意义,为静态方法做到这一点。这是无法确定该方法的调用约定,因而ArgumentException的是更好的选择。

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.

此外,你应该永远不明确抛出一个NullReferenceException。这应该只由CLR被抛出。有明确的时候抛出异常的,通常只能由CLR抛出发生细微的差别。

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.

这也接近以下



  • ArgumentNullException or NullReferenceException from extension method?

这篇关于C#:用于验证&QUOT最佳实践;这&​​QUOT;论点扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 08:59