我有一个 C# 对象的 ObservableCollection。该对象实现了一个接口。我希望能够将对象的 ObservableCollection 转换为接口的 ObservableCollection,而无需解析集合。
例如:
我有一个对象“Guitar”,它实现了一个名为“IMusicalInstrument”的接口。我将 Guitar 对象的 ObservableCollection 绑定到 MyListBox。我希望以下代码行能够将列表框 itemsSource 转换为 ObservableCollection。
ObservableCollection<IMusicalInstrument> InstrumentList =
(ObservableCollection<IMusicalInstrument>)MyListBox.ItemsSource;
目前,这给了我一个 InvalidCastException 。
有没有办法实现这一点(无需解析集合)?
谢谢,
赛斯
I have an ObservableCollection of an object in C#. This object implements an interface. I would like to be able to convert the ObservableCollection of the object to an ObservableCollection of the interface without having to parse through the collection.
So for example:
I have an object "Guitar" which implements an interface called "IMusicalInstrument". I bind an ObservableCollection of Guitar objects to MyListBox. I want the following line of code to be able to convert listbox itemsSource to an ObservableCollection.
ObservableCollection<IMusicalInstrument> InstrumentList =
(ObservableCollection<IMusicalInstrument>)MyListBox.ItemsSource;
Currently, that is giving me an InvalidCastException.
Is there a way to accomplish this (without having to parse through the collection)?
Thanks,
Seth
发布评论
评论(5)
您不能投射它,但是一种方法是将您的迭代包装起来,我知道您想避免但不幸的是不能将其包装到 扩展方法。
这将允许你做一些类似的事情......
这就是我相信你所追求的。
您还可以简单地将
IEnumerable
引用传递到ObservableCollection
的构造函数中...You can not cast it however one approach is to wrap your iteration which I know you want to avoid but unfortunately can't into an extension method.
This would allow you to do something like...
...which is what I believe you are after.
You can also simply pass the
IEnumerable<T>
reference into the constructor ofObservableCollection<T>
...除非
MyListBox.ItemsSource
是ObservableCollection
的实例,否则您无法转换它。Unless
MyListBox.ItemsSource
is an instance ofObservableCollection<IMusicalInstrument>
, then no, you cannot cast it.抱歉,您不能这样做,因为
ObservableCollection
不能被视为ObservableCollection
—— 例如,您不能调用collection.Add(new Frude())
就可以了。Sorry, you can't do this, because an
ObservableCollection<Guitar>
can't be treated as anObservableCollection<IMusicalInstrument>
-- e.g. you can't callcollection.Add(new Flute())
on it.如果您只想管理集合中的项目,那么您可以尝试将 ItemsSource 转换为非泛型 IList。
If you want just manage items of the collection, then you can try to cast ItemsSource to non-generic IList.
如果您只是使用 ObservableCollection 来处理集合更改事件,则可以转换为 INotifyCollectionChanged 并添加事件处理程序。 INotifyCollectionChanged 不使用泛型,因此无论如何您都必须在事件处理程序中进行强制转换。
但是,如果您想枚举 IMusicalInstrument 实例的集合,可以使用 Linq Cast() 扩展方法。例如
希望有帮助!
If you are using ObservableCollection simply to handle collection changed events, you could cast to INotifyCollectionChanged and add your event handler. The INotifyCollectionChanged does not use generics, so you would have to cast in your event handler anyhow.
However, if you want to enumerate your collection of IMusicalInstrument instances, you can use the Linq Cast() extension method. e.g.
Hope that helps!