有一个有趣的怪事 - 认为有人可以提供帮助。
这是来自这个问题的可空类型的一些乐趣:
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。