2009-04-29 130 views
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類的程序集。

回答

4

是的,您需要在繼承時指定類型參數,否則您的EmptyChild也必須是通用的。但是,您不必虛設一個EmptyClass - 只需使用Object作爲您的類型參數:

Public Class EmptyClass 
    Inherits Intermediate(Of Object) 
End Class 
+0

Thanks!我以爲我曾嘗試過使用Object,但它不起作用,但現在我發現它確實如此。 – CoderDennis 2009-04-30 05:43:16