代码之家  ›  专栏  ›  技术社区  ›  Julian Lettner

通过反射订阅可观察的集合

  •  1
  • Julian Lettner  · 技术社区  · 15 年前

    我怎样才能订阅 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 回复  |  直到 15 年前
        1
  •  5
  •   Restuta    15 年前

    可观测采集 器具 不完整收集已更改 接口,因此非常简单:

    ((INotifyCollectionChanged) collection).CollectionChanged += 
            collection_CollectionChanged;
    
        2
  •  1
  •   Garrett    15 年前

    您应该能够订阅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);
        }
    }
    

    它使用一个“magic string”,但它订阅给定的事件处理程序。