我在VB.NET控制台应用程序中有以下示例代码。它编译和工作,但感觉像一个黑客。有没有办法定义EmptyChild,以便它继承Intermediate(Of T As Class)而不使用虚拟EmptyClass?
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
另一种方法是将通用代码移出Base类,然后创建2个这样的中间类:
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将继承通用的Intermediate,而EmptyChild将继承自非通用的Intermediate。我的解决方案的问题是Base类在一个单独的程序集中,我需要保留处理该程序集中的泛型类型的代码。并且Intermediate类中的功能不属于具有Base类的程序集。
答案 0 :(得分:4)
是的,您需要在继承时指定类型参数,或者您的EmptyChild也必须是通用的。但是,您不必假设一个EmptyClass - 只需使用Object作为您的类型参数:
Public Class EmptyClass
Inherits Intermediate(Of Object)
End Class