如何转换和操作未知类型的 ObservableCollection

How to cast and manipulate ObservableCollection of unknown type

(使用 .Net 4.0 版)我正在尝试为 DataGrids 创建一个 WPF AttachedProperty。 属性 将采用一种方法将网格 ItemSource 中的项目从一个索引移动到另一个索引。它假设网格的源集合是 ObservableCollection,这对我来说是安全的。我的计划是将 ItemSource 转换为 ObservableCollection,然后使用集合的 Move 方法。

但是... ObservableCollection 是通用的并且没有基础 class/interface,所以我将 转换为 是什么?类型参数与此方法无关,但也是未知的,因为它设计用于任何 DataGrid。我可以一直使用 Ilist,使用 RemoveInsert,但这可能会不必要地引发 INotifyCollectionChanged 事件,而我正试图避免这种情况。

因为ObservableCollection<T>.Move()没有任何T类型的参数,你可以硬着头皮通过反射调用Move()。我称它为杂乱无章,其他人可能会使用不适合 Stack Overflow 的词,但以下编译、工作并且根本不关心 T 是什么类型。

ObservableCollection<int> foo = new ObservableCollection<int>()
{
    0, 1, 2, 3, 4
};

var method = foo.GetType()
                .GetMethod("Move", 
                    System.Reflection.BindingFlags.Instance 
                        | System.Reflection.BindingFlags.Public);

//  Not a bad idea to check here if method is null before calling it.

method.Invoke(foo, new object[] { 0, 2 });

您可能想改为调用 Type.GetMethods() 并使用 LINQ 搜索结果,这样您就可以防止手头的子类用不同的参数重载 Move() 的罕见情况.

但是 GetMethod()Invoke() 调用根本不关心 ObservableCollection 到底是哪种类型。您将获得您正在寻找的单个 CollectionChanged 事件。