为什么这个扩展方法在VB.NET中抛出NullReferenceException?

从以往的经验来看,我一直觉得在null实例上调用扩展方法是完全合法的(尽管也许不太可取)。所以在C#中,这段代码编译并运行:
// code in static class
static bool IsNull(this object obj) {
    return obj == null;
}

// code elsewhere
object x = null;
bool exists = !x.IsNull();

但是,我刚刚为我的开发团队的其他成员组装了一个小套件示例代码(我们刚刚升级到.NET 3.5,并且我被赋予了让团队加快一些新功能的任务我写的是我以为VB.NET相当于上面的代码,只是发现它实际上是抛出一个NullReferenceException。我写的代码是:

' code in module '
<Extension()> _
Function IsNull(ByVal obj As Object) As Boolean
    Return obj Is nothing
End Function

' code elsewhere '
Dim exampleObject As Object = nothing
Dim exists As Boolean = Not exampleObject.IsNull()

调试器停在那里,好像我调用一个实例方法。我做错了(例如,我在定义C#和VB.NET之间的扩展方法的方式有一些微妙的区别吗?在VB.NET中的null实例上调用扩展方法实际上是不合法的,尽管它在C#中是合法的? (我会以为这是一个.NET的东西,而不是一个特定于语言的东西,但也许我错了)

有人可以向我解释一下吗

您不能在VB.NET中扩展对象类型。

Mainly,we do not allow extension methods to be called off of any expression that is statically typed as “Object”. This was necessary to prevent any existing late bound code you may have written from being broken by extension methods.

参考:

> http://blogs.msdn.com/vbteam/archive/2007/01/24/extension-methods-and-late-binding-extension-methods-part-4.aspx
> http://johnwest.spaces.live.com/Blog/cns!EBA860160D5F5D75!463.entry

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...