是否有必要从一个扩展方法抛出一个NullReferenceException? [英] Is it necessary to throw a NullReferenceException from an extension method?

查看:123
本文介绍了是否有必要从一个扩展方法抛出一个NullReferenceException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义的扩展方法像这样:

If I define an extension method such as this:

static public String ToTitleCase(this string instance, CultureInfo culture)
{
    if (instance == null)
        throw new NullReferenceException();

    if (culture == null)
        throw new ArgumentNullException("culture");

    return culture.TextInfo.ToTitleCase(instance);
}

有必要为我检查空字符串实例,并抛出一个空引用异常自己?还是CLR的对待扩展方法就像在这种情况下,实例方法和处理检查/扔我?

Is it necessary for me to check the string instance for null and throw an null reference exception myself? Or does the CLR treat extension methods like instance methods in this case and handle the checking/throwing for me?

我知道的扩展方法是静态方法只是语法糖,也许C#编译器在编译时检查增加了?请澄清:)

I know extension methods are just syntactic sugar for static methods, perhaps the C# compiler adds in the check at compile time? Please clarify :)

推荐答案

没有。你应该的从不的手动抛出一个的NullReferenceException 。它应该永远只能由框架抛出。

No. You should never throw a NullReferenceException manually. It should only ever be thrown by the framework itself.

在这种情况下,你应该扔 ArgumentNullException 实例文化

In this context, you should be throwing ArgumentNullException for both instance and culture:

static public String ToTitleCase(this string instance, CultureInfo culture)
{
    if (instance == null)
        throw new ArgumentNullException("instance");

    if (culture == null)
        throw new ArgumentNullException("culture");

   return culture.TextInfo.ToTitleCase(instance);
}

从的 的NullReferenceException 文档

请注意应用程序抛出
ArgumentNullException 例外
,而不是
的NullReferenceException 例外
在这里讨论。

Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.

这篇关于是否有必要从一个扩展方法抛出一个NullReferenceException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆