初始化集合类
有没有办法初始化继承类型的类集合?
例如,这是我的代码:
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 对象初始化该列表。
这是不可能的还是有其他方法可以做到这一点?
Is there a way to have a class collection of inherited types be initialized?
For example, here is my code:
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
What I'm doing today for a colllection is:
Public Class Camrys
Property Cars As New List(Of CamryCar) From {New RedCamry, New BlueCamry}
End Class
But this gives me an extra property of Cars
.
I can also do this:
Public Class Camrys
Inherits List(Of CamryCar)
End Class
I prefer this one as I don't have an extra property to deal with. But I can find a way to initialize that that list with objects of RedCamry
and BlueCamry
.
Is it impossible or is there another way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只是另一种选择。我可能会将列表传递给构造函数。我还添加了一个额外的 Sub New() ,它将通过反射初始化集合。
Just another option. I'd probably pass the list in to the constructor. I also added an additional Sub New() that will initialize the collection via reflection.
看来您正在寻找工厂风格的功能。
现在,您可以在任何需要
CamryCar
对象列表的地方使用函数CreateCamrysList
。注意:从
List(Of T)
派生通常是一个糟糕的解决方案。如果您确实需要派生,最好选择Collection(Of T)
。It seems like you're looking for a factory style function.
Now you can use the function
CreateCamrysList
wherever you need the list ofCamryCar
objects.Note: Deriving from
List(Of T)
is in general a bad solution. If you do need to derive it's better to chooseCollection(Of T)
.您需要在构造函数中初始化它:
You need to initialize it in a constructor: