有没有办法初始化一个继承类型的类集合? 例如,这是我的代码: Public Class CamryCar Property Name As String = "Camry" Property Color As StringEnd ClassPublic Class RedCamry Inherits CamryCar Sub New() MyBase.New() C
例如,这是我的代码:
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
我今天要做的事情是:
Public Class Camrys Property Cars As New List(Of CamryCar) From {New RedCamry, New BlueCamry} End Class
但这给了我一个额外的汽车财产.
我也可以这样做:
Public Class Camrys Inherits List(Of CamryCar) End Class
我更喜欢这个,因为我没有额外的财产来处理.但我可以找到一种方法来使用RedCamry和BlueCamry的对象初始化该列表.
这是不可能的还是有另一种方法可以做到这一点?
只是另一种选择.我可能会将列表传递给构造函数.我还添加了一个额外的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