我使用mustInherit Class
我创造了这样的东西
Sub OnLoad
...
Dim o As Object = BaseX(Of Object).LoadItem
dim gv as Gridview = o.AddGridview(myPanel)
...
end Sub
MustInherit Class BaseX(Of T1)
Public Shared Function LoadItem() As Object
...
'Create Item FirstX or SecondX
'return the new Item
...
End Function
Public Function GetGridview(ByVal container As Panel) As Gridview
'return a gridview
End Function
End Class
Class FirstX Inherits BaseX(of A)
...
End Class
Class SecondX Inherits BaseX(of B)
...
End Class
我在“dim gv as Gridview = o.AddGridview(myPanel)”上收到错误
错误18后期绑定分辨率;可能会发生运行时错误。
错误19警告视为错误:后期绑定分辨率;运行 可能会发生错误。
我试试
Dim gv As GridView = DirectCast(o, BaseX(Of Object)).AddGridview(myPanel)
但是我遇到了运行时错误
无法在BaseX
类型上转换对象类型FirstX
如果你有办法去?我应该改变什么?
答案 0 :(得分:0)
您无法将BaseX(Object)强制转换为FirstX,因为FirstX是从BaseX(A)继承的。 即使A继承自Object,BaseX(Of Object)也不是BaseX(A)的父级。
考虑一下:
Class A
public overrides Sub ToString()
Console.Writeline("A")
End Sub
End Class
Class FirstX Inherits BaseX(of A)
public overrides Sub ToString()
A.ToString()
End Sub
End Class
你可以看到BaseX(Of Object).ToString()与BaseX(A).ToString()不同,它是两个完全不同的类,它们不会相互继承。
要解决您的问题,您可以直接转换为FirstX,也可以转换为BaseX(A)。为了可扩展性,我建议创建一个由BaseX(T)实现的接口IBaseX。然后你可以随时向上转到界面。
Interface IBaseX
Function GetGridview(ByVal container As Panel) As Gridview
End Interface
MustInherit Class BaseX(Of T1)
Implements IBaseX
Public Shared Function LoadItem() As Object
...
'Create Item FirstX or SecondX
'return the new Item
...
End Function
Public Function GetGridview(ByVal container As Panel) As Gridview
Implements IBaseX.GetGridView
'return a gridview
End Function
End Class
向上转型:
Dim gv As GridView = CType(o, IBaseX).AddGridview(myPanel)
注意:这是VB.NET代码,它可能无法在Excels VB 6.0中使用