覆盖“基类列表”属性并返回“子类列表”
我有一个基类(例如:Class1),其中包含另一个基类(例如:ClassA)的列表。第一个基类的每个子类(例如:Class1AA,Class1AB,..)包含第二个基类的子类列表(例如:ClassAA,ClassAB,...)
客户端永远不知道正在使用哪个子类,然后我不认为我可以在我的基类中使用泛型。
我尝试了类似这样的事情以及更多,但我总是收到错误..
Imports System.Collections.Generic
Public Class Client
Public Sub DoAction(obj as Class1)
For Each item as ClassA in obj.ItemList
...
Next
End Sub
End Class
Public MustInherit Class Class1
Public MustOverride ReadOnly Property ItemList() As IList(Of ClassA)
End Class
Public Class Class1AA
Inherits Class1
Public Overrides ReadOnly Property ItemList() As IList(Of ClassA)
Get
Return New List(Of ClassAA)
End Get
End Property
End Class
Public Class Class1AB
Inherits Class1
Public Overrides ReadOnly Property ItemList() As IList(Of ClassA)
Get
Return New List(Of ClassAB)
End Get
End Property
End Class
Public Class ClassA
End Class
Public Class ClassAA
Inherits ClassA
End Class
Public Class ClassAB
Inherits ClassA
End Class
感谢您的帮助
I have a base class (ex: Class1) containing a list of another base class (ex: ClassA). Each child class of first base class (ex: Class1AA, Class1AB,..) containing a list of child class of second base class (ex: ClassAA, ClassAB,...)
The client must never know which child class is using, then i don't think i can use generic for my bases classes.
I try something like this and many more, but i always received errors..
Imports System.Collections.Generic
Public Class Client
Public Sub DoAction(obj as Class1)
For Each item as ClassA in obj.ItemList
...
Next
End Sub
End Class
Public MustInherit Class Class1
Public MustOverride ReadOnly Property ItemList() As IList(Of ClassA)
End Class
Public Class Class1AA
Inherits Class1
Public Overrides ReadOnly Property ItemList() As IList(Of ClassA)
Get
Return New List(Of ClassAA)
End Get
End Property
End Class
Public Class Class1AB
Inherits Class1
Public Overrides ReadOnly Property ItemList() As IList(Of ClassA)
Get
Return New List(Of ClassAB)
End Get
End Property
End Class
Public Class ClassA
End Class
Public Class ClassAA
Inherits ClassA
End Class
Public Class ClassAB
Inherits ClassA
End Class
Thanks for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该代码需要通用协方差,而 VB 中不存在该协方差。
基本上,
List(Of Base)
和List(Of Derived)
之间没有任何关系。否则,可以编写以下代码:但是,您可以简单地在任何地方返回一个
List(Of ClassA)
并将派生对象放入该列表中。This code would require generic covariance which doesn’t exist in VB.
Basically there is no relation between a
List(Of Base)
and aList(Of Derived)
. Otherwise, the following code could be written:However, you can simply return a
List(Of ClassA)
everywhere and put derived objects into that list.