无法转换为List(Of point)

时间:2015-11-30 17:03:06

标签: vb.net list ienumerable

我将PointF数组传递给我的函数,将其转换为List(Of Point)。我无法从TypedEnumerable转换为List(Of Point)

Public Shared Function ToListOfPoint(ByVal untypedCollection As IEnumerable) As List(Of Point)
    Return DirectCast(ToEnumerableOfPoint(untypedCollection), List(Of Point))
End Function

Public Shared Function ToEnumerableOfPoint(ByVal untypedCollection As IEnumerable) As IEnumerable(Of Point)
    If untypedCollection Is Nothing Then
        Return Nothing
    ElseIf TypeOf untypedCollection Is IEnumerable(Of Point) Then
        Return DirectCast(untypedCollection, IEnumerable(Of Point))
    ElseIf TypeOf untypedCollection Is IEnumerable(Of PointF) Then
        For Each p As PointF In untypedCollection
            convertedList.Add(ToPoint(p))
        Next
        Return New TypedEnumerable(Of Point)(convertedList)
    Else
        Return New TypedEnumerable(Of Point)(untypedCollection)
    End If
End Function

<Serializable()> _
Public Class TypedEnumerable(Of T)
    Implements IEnumerable(Of T)

    Private wrappedEnumerable As IEnumerable

    ''' <summary>
    ''' Create a typed IEnumerable view
    ''' onto an untyped IEnumerable interface.
    ''' </summary>
    ''' <param name="wrappedEnumerable">IEnumerable interface to wrap.</param>
    Public Sub New(ByVal wrappedEnumerable As IEnumerable)
        MyBase.New()
        Me.wrappedEnumerable = wrappedEnumerable
    End Sub

    Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
        Return New TypedEnumerator(Of T)(Me.wrappedEnumerable.GetEnumerator)
    End Function

    Public Function TypedEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
        Return Me.wrappedEnumerable.GetEnumerator
    End Function

End Class

这两个前两个函数用于生成类TypedEnumerable。我添加了这个

        `ElseIf TypeOf untypedCollection Is IEnumerable(Of PointF) Then
        For Each p As PointF In untypedCollection
            convertedList.Add(ToPoint(p))
        Next
        Return New TypedEnumerable(Of Point)(convertedList)`

让异常消失。我的下一个问题是,有一种更简单的方法可以将一种类型的整个数组转换为另一种类型,而无需遍历每个变量并进行转换吗?

1 个答案:

答案 0 :(得分:1)

您无法直接投射到列表。但是您可以通过在构造函数中传递IEnumerable来创建新的List。尝试:

Public Shared Function ToListOfPoint(ByVal untypedCollection As IEnumerable) As List(Of Point)
    Return New List(untypedCollection)
End Function