2010-01-08 27 views
4

我有以下代碼編譯沒有問題。當然,執行Dim C As IDoThingsC = GetThing_C()時會出現無效的轉換異常。我錯過了什麼嗎?你會想要返回一個不符合函數返回值接口要求的對象嗎?爲什麼接口不是強類型的?

Public Class ClassA 

    Public Sub DoThings_A() 
    Debug.Print("Doing A things...") 
    End Sub 

End Class 


Public Class ClassB 
    Implements IDoThingsC 

    Public Sub DoThings_B() 
    Debug.Print("Doing B things...") 
    End Sub 

    Public Sub DoThings_C() Implements IDoThingsC.DoThings_C 
    Debug.Print("Doing C things...") 
    End Sub 

End Class 


Public Interface IDoThingsC 

    Sub DoThings_C() 

End Interface 


Public Class aTest 

    Public Sub Test() 

    Dim C As IDoThingsC = GetThing_C() 
    C.DoThings_C() 

    End Sub 


    Public Function GetThing_C() As IDoThingsC 

    Dim Thing As ClassA = New ClassA 
    Thing.DoThings_A() 

    Return Thing 

    End Function 


End Class 
+0

我看不出它如何被編譯?我錯過了什麼嗎? – 2010-01-08 19:18:45

+0

這真的*編譯沒有問題嗎?我認爲「GetThing_C」不會被編譯,因爲它試圖將ClassA實例作爲IDoThingsC接口返回,而它並未實現。 – 2010-01-08 19:20:20

+0

這就是我的想法。它在Visual Studio 2005和Visual Studio 2010 Beta 2中編譯。 – JRS 2010-01-08 19:33:01

回答

13

在源代碼文件的頂部使用Option Strict On來捕獲這樣的問題。你會得到一個編譯時錯誤,而不是運行時錯誤:

error BC30512: Option Strict On disallows implicit conversions from 'ClassA' to 'IDoThingsC'. 
+5

用於Option Strict的+1。 – Will 2010-01-08 19:20:10

+6

它是否仍然有可能在這種將會編譯交叉我的手指和希望死去的樂觀方式中編寫VB代碼?爲何還沒有被刪除? – 2010-01-08 19:27:09

+2

當然。更好 - 我在項目的編譯選項中更改了Option Strict選項(這種方式我不必將它添加到每個代碼模塊中)。 – JRS 2010-01-08 19:41:53

1

http://msdn.microsoft.com/en-us/library/h5fsszz9(VS.80).aspx

When converting between data types, the Visual Basic compiler can operate under strict or permissive type semantics. If strict type semantics are in effect, only widening conversions are permitted implicitly, and narrowing conversions must be explicit. Under permissive type semantics, you can attempt all widening and narrowing conversions implicitly. Type semantics apply to conversions between all data types, including object types.

0

選項嚴格採取的措施將解決這個問題。但是「ClassA」也沒有實現任何接口。因此,開關類的定義,下面將解決你的問題:

Public Class ClassA 
    Implements IDoThingsC 

    Public Sub DoThings_A() 
    Debug.Print("Doing A things...") 
    End Sub 

End Class 
相關問題