返回Inherited Generics作为Base Generic

时间:2009-01-26 19:48:54

标签: vb.net generics inheritance

我有BaseAbstractClass(of T as WebControl)(VB Generics),它继承了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

除了使用不同的CustomControl

之外,其他ConcreteWrappers看起来像这样
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

[/编辑]

我能否解释一下发生了什么以及为什么不起作用(可能还有解决方案)?

谢谢!

1 个答案:

答案 0 :(得分: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

  

您不能在具有不同类型参数的泛型类型之间进行转换。专门的泛型类型不构成同一继承树的一部分,因此是不相关的类型。