【发布时间】:2012-09-07 13:58:26
【问题描述】:
有一个有趣的怪事 - 认为有人可以提供帮助。
这个问题的可空类型很有趣:
How to check if an object is nullable?
Option Strict On
Module Test
' Call this overload 1
<Extension()>
Function IsNullable(obj As ValueType) As Boolean
Return False
End Function
' Call this overload 2
<Extension()>
Function IsNullable(Of T As {Structure})(obj As Nullable(Of T)) As Boolean
Return True
End Function
Sub Test()
' a is an integer!
Dim a As Integer = 123
' calling IsNullable as an extension method calls overload 1 and returns false
Dim result1 As Boolean = a.IsNullable()
' calling IsNullable as method calls overload 2 and returns true
Dim result2 As Boolean = IsNullable(a)
' why? surely the compiler should treat both those calls as equivalent
End Sub
End Module
我希望对 IsNullable 的两个调用都会被编译器同等对待,但事实并非如此。即使参数“a”没有改变,扩展方法调用使用与普通方法调用不同的重载。
我的问题是为什么?是什么让编译器在两次调用之间改变主意?
FTR:我们正在使用 Visual Studio 2010、.NET Framework 4。
【问题讨论】:
-
您的问题不清楚“您会认为在 Test sub 中对 IsNullable 的两次调用都会导致使用相同的重载,实际上它们每个都使用不同的重载。”
-
要点 我在我的代码中添加了一些 cmets。希望这能让事情变得清晰。
标签: .net vb.net extension-methods overloading