1
我在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
其他的方式做这将是移动的通用代码出来的基类,然后创建这样第二中级班:
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将从非泛型中间体继承。我的解决方案的问题是基类是在一个单独的程序集中,我需要保留处理该程序集中泛型类型的代码。并且Intermediate类中的功能不属于带有Base类的程序集。
Thanks!我以为我曾尝试过使用Object,但它不起作用,但现在我发现它确实如此。 – CoderDennis 2009-04-30 05:43:16