2009-01-26 64 views
0

我有BaseAbstractClass(of T as WebControl)(VB泛型),它繼承WebControl將繼承的泛型返回爲基類型

BaseAbstractClassConcreteWrapper1ConcreteWrapper2繼承,最後,稍微改動一下,ConcreteWrapper4。其中每一個將繼承BaseAbstractClass使用從WebControl繼承的不同的類。

我想要做的是有工廠返回ConcreteWrapper作爲BaseAbstractClass(of WebControl)。但每當我嘗試返回ConcreteWrapper的新實例時,我都會收到編譯時轉換錯誤。

[編輯:代碼添加]

BaseAbstractClass

Public MustInherit Class BaseAbstractClass(Of T As WebControl) 
    Inherits WebControl 

    Protected _item As T 

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter) 
     _item.RenderControl(writer) 
    End Sub 
End Class 

其他ConcreteWrappers這個樣子,除了與不同CustomControl

Public Class ConcreteWrapper1 
    Inherits BaseAbstractClass(Of CustomControlInheritedFromWebControl1) 

    Public Sub New(ByVal control As CustomControlInheritedFromWebControl1) 
     MyBase._item = control 
    End Sub 
End Class 

Public Class CustomControlInheritedFromWebControl1 
    Inherits WebControl 

    //not the correct comment markers but the coloring works better 
    //do stuff here... Implm not important. 

End Class 

我廠

Public Class WebControlFactory 

    Public Shared Function GetWebControl() As BaseAbstractClass(Of WebControl) 

     Return New ConcreteWrapper1(New CustomControlInheritedFromWebControl1()) 

    End Function 

End Class 

[/編輯]

我可以解釋發生了什麼,爲什麼不起作用(也可能是解決方案)?

謝謝!

+0

發佈代碼段會非常有幫助! – 2009-01-26 19:52:32

回答

2

ConcreteWrapper1不從BaseAbstractClass(of WebControl)繼承,而是從BaseAbstractClass(of T)

BAC(的WebControl的)繼承不與BAC(的T)可互換。

如果您必須使用繼承,則需要兩個抽象級別。

WebControl 
    BAC inherits WebControl 
    BAC(of T) inherits BAC 
     Wrapper1 inherits BAC(of int) 
     Wrapper2 inherits BAC(of string) 
     Wrapper3 inherits BAC(of Foo) 
     Wrapper4 inherits BAC(of Bar) 

然後你可以返回所有Wrappers實例作爲BAC。

原因是Zooba表述得好:

不能泛型類型與不同類型的參數之間進行轉換。專用泛型類型不構成同一繼承樹的一部分,因此不相關類型。

+0

Aaah。真棒。我明白了爲什麼可行,但是我並不完全理解爲什麼BAC(WebControl)和BAC(T作爲WebControl)不兼容。 T被要求是一個WebControl。 – 2009-01-26 20:10:52