通过反射订阅ObservableCollection

时间:2010-06-17 22:19:56

标签: reflection .net-3.5

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

这是.NET版本3.5的问题。我认为4.0会让我的生活much更容易,对吗?

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

感谢您的时间。

2 个答案:

答案 0 :(得分:5)

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

((INotifyCollectionChanged) collection).CollectionChanged += 
        collection_CollectionChanged;

答案 1 :(得分:1)

您应该能够通过一些反思来订阅CollectionChanged:

void AddCollectionChangedHandler(ICollection collection, NotifyCollectionChangedEventHandler handler)
{
    Type type = collection.GetType();
    if(type.IsGenericType
       && type.GetGenericTypeDefinition() == typeof(ObservableCollection<>))
    {
        EventInfo collectionChanged = type.GetEvent("CollectionChanged");
        collectionChanged.AddEventHandler(collection, handler);
    }
}

它使用一个'魔术字符串',但它将给定的处理程序订阅到事件。