興味深い奇妙な点がありました - 誰かが助けてくれるかもしれないと思いました。
これは、この質問からの null 許容型のいくつかの楽しみから生まれました。
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" が変更されていなくても、通常のメソッド呼び出しとは異なるオーバーロードを使用します。
私の質問はなぜですか?コンパイラが 2 つの呼び出しの間で考えを変える理由は何ですか?
FTR: Visual Studio 2010、.NET Framework 4 を使用しています。