1

这是类的布局:

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实现我需要的一些通用功能。TestUserATestUserB需要TestATestB在那里进行处理。但我还需要能够创建单独的实例TestATestB不实例化TestUserAor 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
4

3 回答 3

0

Dim不带 使用,As像这样:

Dim a = New TestUserA()
a.DoOtherStuff()

注意:您需要使用Option Strict Off上述内容才能正常工作。您还可以使用Option Infer On来帮助上面的语法。

于 2013-09-06T14:32:04.680 回答
0

引入一个基类供您TestUser(Of AbstractBase)继承:

Public MustInherit Class TestUser
   Public Sub Print()
      Dim x As AbstractBase = CreateTest()
      x.PrintTest()
   End Sub

   Protected MustOverride Function CreateTest() As AbstractBase 'IMO the type name should really be AbstractTest not AbstractBase 

End Class

然后将基于泛型的工厂实现放入TestUser(Of AbstractBase)

Public Class TestUser(Of T As AbstractBase)
   Inherits TestUser

   Protected Overrides Function CreateTest() As AbstractBase
      Return Activator.CreateInstance(Of T)()
   End Function

End Class

您的 TestUserA 和 TestUserB 没有改变。

现在您的主代码如下所示:

Sub Main()


  Dim a As TestUser = New TestUserA()
  a.Print()

  Dim aTest As New TestA()
  Dim x = aTest.GetTest()

End Sub

Public Function DoThings() As TestUser

  Dim a As TestUser = New TestUserA()
  Return a

End Function

祝你好运!

于 2013-09-06T14:52:10.583 回答
0

您的 TestUser 类应如下所示:

Public Class TestUser

    Public Sub Print(x As AbstractBase)
        x.PrintTest()
    End Sub

End Class

然后你可以像这样打印它:

    Dim a As AbstractBase = New TestA()
    Dim usr As New TestUser
    usr.Print(a)
于 2013-09-06T14:52:17.487 回答