2010-10-04 163 views
4

是否有辦法讓類繼承類的集合被初始化?初始化集合類

例如,這裏是我的代碼:

Public Class CamryCar 
    Property Name As String = "Camry" 
    Property Color As String 
End Class 

Public Class RedCamry 
    Inherits CamryCar 
    Sub New() 
     MyBase.New() 
     Color = "Red" 
    End Sub 
End Class 

Public Class BlueCamry 
    Inherits CamryCar 
    Sub New() 
     MyBase.New() 
     Color = "Blue" 
    End Sub 
End Class 

我在做什麼今天的colllection是:

Public Class Camrys 
    Property Cars As New List(Of CamryCar) From {New RedCamry, New BlueCamry} 
End Class 

但是這給了我的Cars額外的屬性。

我也可以這樣做:

Public Class Camrys 
    Inherits List(Of CamryCar) 
End Class 

我喜歡這個,因爲我沒有額外的屬性來處理。但我可以通過RedCamryBlueCamry的對象找到一種方法來初始化該列表。

難道還有其他方法可以做到嗎?

回答

2

只是另一種選擇。我可能會將該列表傳遞給構造函數。我還添加了一個額外的Sub New(),它將通過反射初始化集合。

Imports System.Reflection 

Module Module1 

    Sub Main() 
     Dim camrys As New Camrys 

     For Each camry As CamryCar In camrys 
      Console.WriteLine(camry.Color) 
     Next 

     Console.ReadKey() 
    End Sub 

End Module 

Public Class Car 

End Class 

Public Class CamryCar 
    Inherits Car 
    Property Name As String = "Camry" 
    Property Color As String 
End Class 

Public Class RedCamry 
    Inherits CamryCar 
    Sub New() 
     MyBase.New() 
     Color = "Red" 
    End Sub 
End Class 

Public Class BlueCamry 
    Inherits CamryCar 
    Sub New() 
     MyBase.New() 
     Color = "Blue" 
    End Sub 
End Class 

Public Class Camrys 
    Inherits List(Of CamryCar) 

    Public Sub New(ByVal Camrys As List(Of CamryCar)) 
     MyBase.New() 

     For Each Camry As CamryCar In Camrys 
      Add(Camry) 
     Next 
    End Sub 

    Public Sub New() 
     MyBase.New() 
     InitializeCamrys() 
    End Sub 

    Public Sub InitializeCamrys() 
     Dim asm As Assembly = Assembly.GetExecutingAssembly() 

     For Each t As Type In asm.GetTypes() 
      If GetType(CamryCar) Is t.BaseType Then 
       Dim camry As CamryCar = Activator.CreateInstance(t) 
       Add(camry) 
      End If 
     Next 
    End Sub 

End Class 
+0

+1用於使用反射自動添加所有版本的CamryCar。 – awe 2010-10-20 08:13:52

+0

謝謝。我認爲這很聰明。 :) – 2010-10-20 14:21:31

+0

輝煌!謝謝。 – Stan 2010-10-20 17:15:36

1

看起來你正在尋找工廠風格的功能。現在

Module Factory 

    Public Function CreateCamrysList As List(of CamryCar) 
    Return New List(Of CamryCar) From {New RedCamry, New BlueCamry} 
    End Function 

End Module 

只要您需要CamryCar對象列表,你可以使用函數CreateCamrysList

注:List(Of T)導出通常是一個不好的解決方案。如果你確實需要推導出更好的選擇Collection(Of T)

+2

出於好奇,爲什麼從List(Of T)得出一個不好的解決方案? – Stan 2010-10-05 04:21:27

1

你需要在構造函數初始化:

Public Class Camrys 
    Inherits List(Of CamryCar) 

    Public Sub New() 
     MyBase.New() 
     Add(New RedCamry()) 
     Add(New BlueCamry()) 
    End Sub 

End Class