无法投射到列表(点)

Unable to cast to List(Of point)

我正在将一个 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

前两个函数用于生成 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)`

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

您不能直接转换为列表。但是您可以通过在构造函数中传递 IEnumerable 来创建一个新的列表。尝试:

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