0

我与 mustInherit 类一起工作

我创造了一些看起来像这样的东西

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)

但我遇到了运行时错误

无法将对象类型 FirstX 转换为 BaseX 类型

如果你有路要走?我应该改变什么?

4

1 回答 1

0

您不能将 BaseX(of Object) 转换为 FirstX,因为 FirstX 是从 BaseX(of A) 继承的。即使 A 继承自 Object,BaseX(Of Object) 也不是 BaseX(of 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(of A).ToString() 不同,它是两个完全不同的类,它们不从另一个继承。

要解决您的问题,您可以直接转换为 FirstX 或 BaseX(of A)。为了可扩展性,我建议创建一个由 BaseX(of 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

于 2013-02-07T21:36:03.100 回答