【问题标题】:Unable to cast to List(Of point)无法投射到列表(点)
【发布时间】:2015-11-30 17:03:05
【问题描述】:

我将一个 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)`

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

【问题讨论】:

  • 尝试调用.ToList()
  • 这是PointF 或Point 的数组?除此之外,就像 Yacoub Massad 所说,使用.ToList()
  • @GlorinOakenfoot 它是一个 PointF 数组,我返回一个 List(Of Point)

标签: vb.net list ienumerable


【解决方案1】:

您不能直接投射到列表。但是您可以通过在构造函数中传递 IEnumerable 来创建一个新列表。试试:

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

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2014-08-08
    • 2012-04-29
    • 2014-06-04
    相关资源
    最近更新 更多