gpt4 book ai didi

.net - 为什么此扩展方法在VB.NET中引发NullReferenceException?

转载 作者:行者123 更新时间:2023-12-03 11:27:55 26 4
gpt4 key购买 nike

根据以前的经验,我一直认为在空实例上调用扩展方法是完全合法的(尽管可能不建议这样做)。因此,在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之间定义扩展方法的方式有细微的差别)?尽管在C#中合法,但在VB.NET中对空实例调用扩展方法实际上是 而不是合法吗? (我本以为这是.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
  • 关于.net - 为什么此扩展方法在VB.NET中引发NullReferenceException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2402660/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com