C# 我如何转换成 ObservableCollection<object>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1198751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:40:10  来源:igfitidea点击:

How can i cast into a ObservableCollection<object>

c#observablecollectioncovariance

提问by Mario Binder

How can i cast

我怎么投

from ObservableCollection<TabItem> into ObservableCollection<object>

this doesnt work for me

这对我不起作用

(ObservableCollection<object>)myTabItemObservableCollection

采纳答案by Arsen Mkrtchyan

you should copy like this

你应该像这样复制

return new ObservableCollection<object>(myTabItemObservableCollection);

回答by AnthonyWJones

You can't. ObservableCollection<TabItem>does not derive from ObservableCollection<object>.

你不能。ObservableCollection<TabItem>不源自ObservableCollection<object>.

If you explain why you would want to perhaps we can point out an alternative interface you can use.

如果你解释为什么你想要,也许我们可以指出你可以使用的替代界面。

回答by Marc Gravell

Basically, you can't. Not now, and not in .NET 4.0.

基本上,你不能。不是现在,也不是在 .NET 4.0 中

What is the context here? What do you need? LINQ has Cast<T>which can get you the data as a sequence, or there are some tricks with generic methods (i.e. Foo<T>(ObservalbleCollection<T> col)etc).

这里的背景是什么?你需要什么?LINQCast<T>可以让您将数据作为 序列,或者有一些通用方法(即Foo<T>(ObservalbleCollection<T> col)等)的技巧。

Or you can just use the non-generic IList?

或者你可以只使用非通用的IList

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

回答by Hath

you could use IEnumerable.Cast<T>()

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

回答by Mario Binder

thanx for all answers, but I think I have solve this problem self with a "helpermethode".

感谢所有答案,但我想我已经用“帮助方法”解决了这个问题。

Perhaps has any a better method or a linq statement for this.

也许对此有更好的方法或 linq 语句。

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

回答by A. K.

None of the examples I have found have worked for me, I have cobbled together the below code and it seems to work. I have a hierarchy that is created by deserializing an XML file and I am able to loop through all the objects in the hierarchy, but you can adapt this to just loop through one ObservableCollection and get the objects as objects and not strongly typed.

我发现的所有例子都没有对我有用,我拼凑了下面的代码,它似乎有效。我有一个通过反序列化 XML 文件创建的层次结构,我能够遍历层次结构中的所有对象,但是您可以将其调整为仅遍历一个 ObservableCollection 并将对象作为对象而不是强类型。

I want to add a PropertyChangingEventHandler to every property in the hierarchy so that I can implement undo/redo functionality.

我想为层次结构中的每个属性添加一个 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
                    }
                }
            }
        }
    }
}

The method is just called like this

方法就是这样调用的

TraversalHelper.TraverseAndExecute(object);

If you just want to create a collection of objects you just need this bit of code

如果你只想创建一个对象集合,你只需要这段代码

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
}

回答by G Clovs

You can Cast it as INotifyCollectionChanged;

您可以将其转换为 INotifyCollectionChanged;

Like:

喜欢:

if (myTabItemObservableCollection is INotifyCollectionChanged collection)
{
   Do Stuff
}