通过反射订阅ObservableCollection

Jul*_*ner 1 reflection .net-3.5

如何在ObservableCollection<??>不知道集合的元素类型的情况下订阅?没有太多的"魔法字符串",有没有办法做到这一点?

这是.NET版本3.5的问题.我认为4.0会让我的生活轻松,对吧?

Type type = collection.GetType();
if(type.IsGenericType 
   && type.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
{
    // I cannot cast the collection here
    ObservableCollection<object> x = collection;
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的时间.

Res*_*uta 5

ObservableCollection实现了INotifyCollectionChanged接口,因此它可以非常简单:

((INotifyCollectionChanged) collection).CollectionChanged += 
        collection_CollectionChanged;
Run Code Online (Sandbox Code Playgroud)