在C#中,当你调用一个空对象上的扩展方法会发生什么? [英] In C#, what happens when you call an extension method on a null object?

查看:280
本文介绍了在C#中,当你调用一个空对象上的扩展方法会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问该方法被调用一个空值,或者没有给出一个空引用异常?

Does the method get called with a null value or does it give a null reference exception?

MyObject myObject = null;
myObject.MyExtensionMethod(); // <-- is this a null reference exception?

如果这是我永远不会需要检查我的'这个'参数为空的情况?

If this is the case I will never need to check my 'this' parameter for null?

推荐答案

这将正常工作(不例外)。扩展方法不使用虚拟电话(即它使用呼IL指令,而不是callvirt),所以没有空检查,除非你把它写自己的扩展方法。这实际上是有用在少数情况下:

That will work fine (no exception). Extension methods don't use virtual calls (i.e. it uses the "call" il instruction, not "callvirt") so there is no null check unless you write it yourself in the extension method. This is actually useful in a few cases:

public static bool IsNullOrEmpty(this string value)
{
    return string.IsNullOrEmpty(value);
}
public static void ThrowIfNull<T>(this T obj, string parameterName)
        where T : class
{
    if(obj == null) throw new ArgumentNullException(parameterName);
}

从根本上讲,调用静态调用非常字面 - 即

Fundamentally, calls to static calls are very literal - i.e.

string s = ...
if(s.IsNullOrEmpty()) {...}

变成了:

string s = ...
if(YourExtensionClass.IsNullOrEmpty(s)) {...}

在这里显然是有没有空的检查。

where there is obviously no null check.

这篇关于在C#中,当你调用一个空对象上的扩展方法会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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