當一個參數是接口時,Visual Studio似乎停止類型檢查函數參數。類型檢查VB.Net中的函數接口參數的樂趣
考慮以下幾點:
' An interface and the class that implements it:
Public Interface IA
End Interface
Public Class A
Implements IA
End Class
' Another reference type for the demonstration:
Public Class MyReferenceType
End Class
' A function that uses IA as the type of one of its parameters:
Private Function SomeFunc(ByVal a As IA, ByVal r As MyReferenceType)
Return Nothing
End Sub
,這裏是的類型檢查問題的例子:
Private Sub Example()
Dim a As IA = New A
Dim r As New MyReferenceType
' Some other random reference type, choose any
' other reference type you like
Dim list As New List(Of String)
' Each of these calls to SomeFunc compile without errors.
SomeFunc(r, r)
SomeFunc(r, a)
SomeFunc(list, r)
SomeFunc(list, a)
' Does not compile due to type mismatch
'SomeFunc(list, list)
End Sub
正如我的評論暗示,這個代碼編譯好,在編輯器中沒有錯誤或者。如果我執行程序,雖然我得到System.InvalidCastException
,這並不令人意外。我猜這是編譯器中的一個類型檢查錯誤?我正在使用Visual Studio 2005,所以這是在VS的更高版本中修復的嗎?
你是對的!我必須以某種方式關閉Option Strict,MSDN表示默認狀態爲開啓。 – AuGambit 2012-03-04 15:22:05