这是类的布局:
Public MustInherit Class AbstractBase
Public MustOverride Function GetTest() As String
Public Sub PrintTest()
System.Console.WriteLine(Me.GetTest())
End Sub
End Class
Public Class TestA
Inherits AbstractBase
Public Overrides Function GetTest() As String
Return "Hello from A"
End Function
End Class
Public Class TestB
Inherits AbstractBase
Public Overrides Function GetTest() As String
Return "Hello from B"
End Function
End Class
Public Class TestUser(Of T As AbstractBase)
Public Sub Print()
Dim x As AbstractBase = Activator.CreateInstance(Of T)()
x.PrintTest()
End Sub
End Class
Public Class TestUserA
Inherits TestUser(Of TestA)
''' Custom TestUserA code
End Class
Public Class TestUserB
Inherits TestUser(of TestB)
''' Custom TestUserB Stuff
End Class
这是问题区域:
Dim a As TestUser(Of AbstractBase) = New TestUserA()
编译器说它们TestUserA
不能被强制转换为TestUser(Of AbstractBase)
. 我不确定为什么,因为TestUserA
继承自TestUser(Of TestA)
和TestA
继承自AbstractBase
. 对我来说,这个继承结构看起来是正确的,所以我不确定为什么这不起作用?
这个想法是AbstractBase
实现我需要的一些通用功能。TestUserA
并TestUserB
需要TestA
并TestB
在那里进行处理。但我还需要能够创建单独的实例TestA
和TestB
不实例化TestUserA
or TestUserB
。
这样我就可以做到:
Dim a As TestUser(Of AbstractBase) = New TestUserA()
a.Print()
Dim aTest As New TestA()
Dim x = aTest.GetTest()
Public Function DoThings() As TestUser(Of AbstractBase)
Dim a As TestUser(Of AbstractBase) = New TestUserA()
return a
End Function