如何将数据添加到ObservableCollection<object>集合中?

13

我怎样可以进行类型转换?

from ObservableCollection<TabItem> into ObservableCollection<object>

这对我没用

(ObservableCollection<object>)myTabItemObservableCollection

2
那被称为协变性,而在C#中尚不可用。 - Ed S.
2
(并且对于集合,它们在4.0中也不可用 - 只是为了明确起见) - Marc Gravell
7个回答

14

你应该像这样复制

return new ObservableCollection<object>(myTabItemObservableCollection);

1
.NET 4并没有像Marc Gravell的帖子中详细说明的那样解决这个问题。 - MrSlippers

12

基本上,你做不到。现在不行,即使在 .NET 4.0 中也不行

这里的背景是什么?你需要什么?LINQ有Cast<T>可以将数据作为序列获取,或者可以使用一些通用方法的技巧(例如Foo<T>(ObservalbleCollection<T> col)等)。

或者你可以只使用非泛型的IList

IList untyped = myTypedCollection;
untyped.Add(someRandomObject); // hope it works...

4

你可以使用 IEnumerable.Cast<T>()


0

感谢所有答案,但我认为我已经用一个“helpermethode”自行解决了这个问题。

也许有更好的方法或linq语句可供使用。

private void ConvertTabItemObservableCollection()
{
  Manager manager = this.container.Resolve<Manager>();
  foreach (var tabItem in manager.ObjectCollection)
  {
    TabItemObservableCollection.Add((TabItem)tabItem);
  }
}

由于我们不知道ObjectCollection的类型,因此很难回答... - Marc Gravell
我不明白你的意思!我有一个TabItem,我想将其添加到类型为object的ObservableCollection中。 "Manager"是一个全局类,具有我在Prism应用程序中任何视图/组件中需要的ObservableCollection<object>。 - Mario Binder
啊,抱歉我误解了你的回答。"ObjectCollection" 的类型是 object ObservableCollection<object>。 - Mario Binder
是的,但我的答案不是更短吗?用较少的代码以相同的方式解决了同样的问题。 - Arsen Mkrtchyan

0

不行。 ObservableCollection<TabItem> 不是从 ObservableCollection<object> 派生的。

如果您解释一下为什么想要这样做,也许我们可以指出您可以使用的替代接口。


0

我找到的所有示例都没有对我起作用,我拼凑出了下面的代码,它似乎可以工作。我有一个由反序列化XML文件创建的层次结构,我能够循环遍历层次结构中的所有对象,但您可以将其调整为仅循环遍历一个ObservableCollection并获取对象作为对象而不是强类型。

我想在层次结构中的每个属性上添加PropertyChangingEventHandler,以便我可以实现撤消/重做功能。

public static class TraversalHelper
{

    public static void TraverseAndExecute(object node)
    {
        TraverseAndExecute(node, 0);
    }

    public static void TraverseAndExecute(object node, int level)
    {
        foreach (var property in node.GetType().GetProperties())
        {
            var propertyValue = node.GetType().GetProperty(property.Name).GetGetMethod().Invoke(node, null); // Get the value of the property
            if (null != propertyValue)
            {
                Console.WriteLine("Level=" + level + " :  " + property.Name + " :: " + propertyValue.GetType().Name); // For debugging
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(ObservableCollection<>)) // Check if we are dealing with an observable collection
                {
                    //var dummyvar = propertyValue.GetType().GetMethods();   // This was just used to see which methods I could find on the Collection
                    Int32 propertyValueCount = (Int32)propertyValue.GetType().GetMethod("get_Count").Invoke(propertyValue, null); // How many objects in the collection
                    level++;
                    for (int i = 0; i < propertyValueCount; i++) // Loop over all objects in the Collection
                    {
                        object properyValueObject = (object)propertyValue.GetType().GetMethod("get_Item").Invoke(propertyValue, new object[] { i }); // Get the specified object out of the Collection
                        TraverseAndExecute(properyValueObject, level); // Recursive call in case this object is a Collection too
                    }
                }
            }
        }
    }
}

这个方法就是这样调用的

TraversalHelper.TraverseAndExecute(object);

如果您只想创建一个对象集合,您只需要这段代码。
ObservableCollection<Field> typedField = migration.FileDescriptions[0].Inbound[0].Tables[0].Table[0].Fields[0].Field; // This is the strongly typed decalaration, a collection of Field objects
object myObject = typedField; // Declare as object
Int32 propertyValueCount = (Int32)myObject.GetType().GetMethod("get_Count").Invoke(myObject, null); // How many objects in this Collection
for (int i = 0; i < propertyValueCount; i++) // Loop over all objects in the Collection
{
    object properyValueObject = (object)myObject.GetType().GetMethod("get_Item").Invoke(myObject, new object[] { i }); // Get the specified object out of the Collection, in this case a Field object
    // Add the object to a collection of objects, or whatever you want to do with object
}

-1

你可以将它转换为INotifyCollectionChanged;

例如:

if (myTabItemObservableCollection is INotifyCollectionChanged collection)
{
   Do Stuff
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接