如何使用通用列表来获取实现公共接口的派生类

时间:2012-02-14 03:28:12

标签: .net generics

假设我有一个通用接口(VB.NET):

Public Interface IBase(Of T As {IBase(Of T)})
    Property Parent() As T

我有两个实现接口的类

Public Class Derive1
    Implements IBase(Of Derive1)
    Public Property Parent() As Derive1 Implements IBase(Of Derive1).Parent

Public Class Derive2
    Implements IBase(Of Derive2)
    Public Property Parent() As Derive2 Implements IBase(Of Derive2).Parent

如何使用可以接受Derive1和Derive2的通用List,以便:

genList.Add(Derive1)
genList.Add(Derive2)

1 个答案:

答案 0 :(得分:0)

让Derive1和Derive2实现一个通用接口,然后创建该接口的List。例如,假设您要迭代通用列表并拥有一个可以在该列表中的Derive1和Derive2对象上执行的方法(如CountChildren)。首先,您需要创建一个界面,如下所示:

Public Interface ICalculations
    Function CountChildren() As Integer
End Interface

然后,您将要设置Derive1和Derive2,以便它们实现此接口。这可能是这样的:

Public Class Derive1
    Implements IBasicPortfolio(Of Derive1)
    Implements ICalculations
    Public Property Value() As Integer
        Get
            Return m_Value
        End Get
        Set
            m_Value = Value
        End Set
    End Property
    Private m_Value As Integer
    Public Property [Next]() As Derive1
        Get
            Return m_Next
        End Get
        Set
            m_Next = Value
        End Set
    End Property
    Private m_Next As Derive1
    Public Function CountChildren() As Integer
        Return 1 + [Next].CountChildren()
    End Function
End Class

Public Class Derive2
    Implements IBasicPortfolio(Of Derive2)
    Implements ICalculations
    Public Property Value() As Integer
        Get
            Return m_Value
        End Get
        Set
            m_Value = Value
        End Set
    End Property
    Private m_Value As Integer
    Public Property [Next]() As Derive1
        Get
            Return m_Next
        End Get
        Set
            m_Next = Value
        End Set
    End Property
    Private m_Next As Derive1
    Public Function CountChildren() As Integer
        Return 1 + [Next].CountChildren()
    End Function
End Class

然后你可以创建一个ICalculations列表,它可以包含Derive1和Derive2对象:

Dim foo = New List(Of ICalculations)()

foo.Add(New Derive1())
foo.Add(New Derive2())

For Each bar As var In foo
    bar.CountChildren()
Next