将继承的泛型返回为基类型
我有BaseAbstractClass(of T as WebControl)
(VB泛型),它继承WebControl
。将继承的泛型返回为基类型
BaseAbstractClass
由ConcreteWrapper1
,ConcreteWrapper2
继承,最后,稍微改动一下,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
[/编辑]
我可以解释发生了什么,为什么不起作用(也可能是解决方案)?
谢谢!
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表述得好:
不能泛型类型与不同类型的参数之间进行转换。专用泛型类型不构成同一继承树的一部分,因此不相关类型。
Aaah。真棒。我明白了为什么可行,但是我并不完全理解为什么BAC(WebControl)和BAC(T作为WebControl)不兼容。 T被要求是一个WebControl。 – 2009-01-26 20:10:52
发布代码段会非常有帮助! – 2009-01-26 19:52:32