开发者

Overrides a "list of base class" property and returning a "list of child 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, Clas开发者_开发百科sAB,...)

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


This code would require generic covariance which doesn’t exist in VB.

Basically there is no relation between a List(Of Base) and a List(Of Derived). Otherwise, the following code could be written:

Dim a As New List(Of Base)()
a.Add(New Base())

Dim b As List(Of Derived) = a
''// Can’t work: b(0) doesn’t contain a `Derived` instance!
Dim x As Derived = b(0)

However, you can simply return a List(Of ClassA) everywhere and put derived objects into that list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜