एक दिलचस्प अजीबता मिली - सोचा कि कोई मदद करने में सक्षम हो सकता है।वीबी.नेट कंपाइलर कैसे चलने के लिए कौन सा एक्सटेंशन ओवरलोड चुनता है?
यह इस सवाल से नल प्रकार के साथ कुछ मज़ा से बाहर आया:
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 के दोनों कॉल माना जाएगा संकलक द्वारा एक ही है, लेकिन यह नहीं है मुकदमा। विस्तार विधि कॉल सामान्य विधि कॉल में एक अलग अधिभार का उपयोग करता है भले ही तर्क "ए" अपरिवर्तित है।
मेरा प्रश्न है क्यों? क्या कंपेलर दो कॉल के बीच अपना मन बदलता है?
FTR: हम दृश्य स्टूडियो 2010 का उपयोग कर रहे हैं, .NET फ़्रेमवर्क 4
आपका प्रश्न वास्तव में वे एक, स्पष्ट "आप टेस्ट उप ही अधिभार में परिणाम होगा में IsNullable के दोनों कॉल इस्तेमाल किया जा रहा लगता होगा नहीं है एक अलग का उपयोग करें। " –
पॉइंट लिया गया मैंने अपने कोड में कुछ टिप्पणियां जोड़ दी हैं। उम्मीद है कि यह चीजों को स्पष्ट करता है। –