2013-03-14 95 views
0

有一个集合对象。我需要捕获这个集合的每个单个对象来处理该单个对象。Cast ObservableCollection of(unknown)

我已经决定与接口进来的对象:

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)) 

它抛出异常(德国):

Das Objekt des Typs “System.Collections.ObjectModel.ObservableCollection 1[OwnSpecialClass]" kann nicht in Typ "System.Collections.ObjectModel.Collection 1 [System.Object]” umgewandelt werden。

如何将此集合投射到任何ObservableCollection,如果OwnSpecialClass不可用并且只是已知的对象。

我的测试:

Exception screenshot

回答

0

我不能完全肯定,如果这是你在问什么,所以如果不是我道歉,但这里是如何从一个更具体的观察集合下来改变定期收集,反之亦然。这是一个昂贵的操作。

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)()) 
+0

您示例中的observableCollection(第一个代码行)仅作为Object传输,现在的问题是如何将其转换为ObservableCollection(在您的示例中名为collection的第二个代码行) – Nasenbaer 2013-03-15 09:32:25

0

使用下面的代码做的工作

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 

但因为每个项目需要进行铸造转换器是不是巨大的高性能。

相关问题