有没有办法初始化一个继承类型的类集合?
例如,这是我的代码:
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
但是这给了我Cars
的额外属性。
我也可以这样做:
Public Class Camrys
Inherits List(Of CamryCar)
End Class
我更喜欢这个,因为我没有额外的财产来处理。但我可以找到一种方法来初始化包含RedCamry
和BlueCamry
对象的列表。
这是不可能的还是有另一种方法可以做到这一点?
答案 0 :(得分: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
答案 1 :(得分:1)
看起来你正在寻找工厂风格的功能。
Module Factory
Public Function CreateCamrysList As List(of CamryCar)
Return New List(Of CamryCar) From {New RedCamry, New BlueCamry}
End Function
End Module
现在,您可以在任何需要CreateCamrysList
对象列表的地方使用函数CamryCar
。
注意:从List(Of T)
派生通常是一个糟糕的解决方案。如果你确实需要派生它,最好选择Collection(Of T)
。
答案 2 :(得分:1)
您需要在构造函数中初始化它:
Public Class Camrys
Inherits List(Of CamryCar)
Public Sub New()
MyBase.New()
Add(New RedCamry())
Add(New BlueCamry())
End Sub
End Class