Vb.net 我可以从泛型类继承而不指定类型吗?
我在VB.NET控制台应用程序中有以下示例代码。它可以编译并工作,但感觉像是黑客。有没有一种方法可以定义EmptyChild,这样它就可以在不使用伪EmptyClass的情况下从Intermediate(作为类的T)继承Vb.net 我可以从泛型类继承而不指定类型吗?,vb.net,generics,inheritance,Vb.net,Generics,Inheritance,我在VB.NET控制台应用程序中有以下示例代码。它可以编译并工作,但感觉像是黑客。有没有一种方法可以定义EmptyChild,这样它就可以在不使用伪EmptyClass的情况下从Intermediate(作为类的T)继承 Module Module1 Sub Main() Dim Child1 = New RealChild() Child1.Content = New RealClass() Dim Child2 = New EmptyChild() Con
Module Module1
Sub Main()
Dim Child1 = New RealChild()
Child1.Content = New RealClass()
Dim Child2 = New EmptyChild()
Console.WriteLine("RealChild says: " & Child1.Test)
Console.WriteLine("EmptyChild says: " & Child2.Test)
Console.ReadLine()
End Sub
Public Class EmptyClass
End Class
Public Class RealClass
Public Overrides Function ToString() As String
Return "This is the RealClass"
End Function
End Class
Public MustInherit Class Base(Of T As Class)
Private _content As T = Nothing
Public Property Content() As T
Get
Return _content
End Get
Set(ByVal value As T)
_content = value
End Set
End Property
Public Overridable Function Test() As String
If Me._content IsNot Nothing Then
Return Me._content.ToString
Else
Return "Content not initialized."
End If
End Function
End Class
Public MustInherit Class Intermediate(Of T As Class)
Inherits Base(Of T)
'some methods/properties here needed by Child classes
End Class
Public Class RealChild
Inherits Intermediate(Of RealClass)
'This class needs all functionality from Intermediate.
End Class
Public Class EmptyChild
Inherits Intermediate(Of EmptyClass)
'This class needs some functionality from Intermediate,
' but not the Content as T property.
Public Overrides Function Test() As String
Return "We don't care about Content property or Type T here."
End Function
End Class
End Module
另一种方法是将泛型代码移出基类,然后创建两个中间类,如下所示:
Public MustInherit Class Intermediate
Inherits Base
'some methods/properties here needed by Child classes
End Class
Public MustInherit Class Intermediate(Of T As Class)
Inherits Intermediate
'implement generic Content property here
End Class
然后RealChild将从泛型中间层继承,EmptyChild将从非泛型中间层继承。该解决方案的问题是基类位于单独的程序集中,我需要在该程序集中保留处理泛型类型的代码。中间类中有一些功能不属于具有基类的程序集中。是的,继承时需要指定类型参数,或者EmptyChild也必须是泛型的。但是,您不必虚构一个EmptyClass,只需使用Object作为您的类型参数:
Public Class EmptyClass
Inherits Intermediate(Of Object)
End Class
谢谢我以为我试过使用Object,但它不起作用,但现在我看到它起作用了。