【问题标题】:Cast ObservableCollection of (unknown)投射 ObservableCollection 的(未知)
【发布时间】:2013-03-14 17:07:19
【问题描述】:

有一个集合对象。我需要捕获此集合中的每个对象以使用该单个对象。

我已经确定了带有接口的传入对象:

TypeOf Src Is System.Collections.IList = TRUE 
TypeOf Src Is System.Collections.Generic.IEnumerable(Of Object) = TRUE

现实中的对象是

System.Collections.ObjectModel.ObservableCollection(Of OwnSpecialClass)

当投射这个传入对象时

NewCollection = CType(MySourceCollection, System.Collections.ObjectModel.Collection(Of Object))

它抛出异常(德语):

类型对象 “System.Collections.ObjectModel.ObservableCollection1[OwnSpecialClass]" kann nicht in Typ "System.Collections.ObjectModel.Collection1[System.Object]” umgewandelt werden。

如果 OwnSpecialClass 不可用且仅称为对象,如何将此集合转换为任何 ObservableCollection。

我的测试:

【问题讨论】:

    标签: .net collections casting ienumerable


    【解决方案1】:

    我不完全确定这是否是您所要求的,如果不是,我深表歉意,但这里是您如何从更具体的可观察集合更改为常规集合的方法,反之亦然。这是一个有点昂贵的操作。

    Dim observableCollection As New System.Collections.ObjectModel.ObservableCollection(Of String)()
    Dim collection As New System.Collections.ObjectModel.Collection(Of Object)(observableCollection.Cast(Of Object)().ToList())
    
    'or in reverse...'
    
    Dim collection As New System.Collections.ObjectModel.Collection(Of Object)()
    Dim observableCollection As New System.Collections.ObjectModel.ObservableCollection(Of String)(collection.Cast(Of String)())
    

    【讨论】:

    • observableCollection 在您的示例中(第一个代码行)仅作为 Object 传输,现在的问题是,如何将其转换为 ObservableCollection (命名为 collection 中的第二个代码行你的例子)
    【解决方案2】:

    使用以下代码完成工作

     If TypeOf Src Is System.Collections.IList Then
    
         Dim IListTmp As System.Collections.IList = CType(Src, System.Collections.IList)
         Dim IListTmpItems(IListTmp.Count - 1) As Object
         IListTmp.CopyTo(IListTmpItems, 0)
    
         For Each O As Object In IListTmpItems
              'Whatever you want to do with that object now.... ex: result = result & O.ToString() & "|"
         Next
     End If
    

    但转换器的性能并不高,因为每个项目都需要转换。

    【讨论】:

      猜你喜欢
      • 2023-01-20
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多