1

當一個參數是接口時,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的更高版本中修復的嗎?

回答

1

我相信這是因爲你有Option Strict關閉。如果您打開Option Strict開始,您的代碼無法編譯,正如我們所期望的那樣。

需要注意的是這樣的:

SomeFunc(list, a) 

是不是這樣:

SomeFunc(list, list) 

在第一種情況下,當Option Strict爲關閉時,編譯器將有效地爲你鑄造。畢竟,類型IA的值可以是MyReferenceType

在第二種情況下,List(Of String)值不能永遠MyReferenceType兼容(與Nothing ...值的有爭議的除外),所以即使使用選項嚴格關閉,編譯失敗。編譯器不會讓你嘗試一些無法工作的東西。

道德故事:爲了更好的類型檢查,請關閉Option Strict。

+0

你是對的!我必須以某種方式關閉Option Strict,MSDN表示默認狀態爲開啓。 – AuGambit 2012-03-04 15:22:05