使用反射订阅的事件未触发

本文关键字:事件 反射 | 更新日期: 2023-09-27 18:18:21

我有这样的代码:

var listProperty = typeof(WebserviceUtil).GetProperty("List" + typeof(T).Name);
var mainList = (ObservableCollection<T>)listProperty.
    GetValue(WebserviceUtil.Instance, null);
mainList.CollectionChanged += new NotifyCollectionChangedEventHandler(
    AllItems_CollectionChanged);

然而,AllItems_CollectionChanged方法永远不会被调用。

有谁能告诉我为什么吗?

编辑

我有几个列表,例如:

public ObservableCollection<Banana> ListBanana { get; private set; }
public ObservableCollection<Book> ListBook { get; private set; }
// ...
public ObservableCollection<Officer> ListOfficer { get; private set; }

和I 确实希望避免必须手动(un)订阅它们的CollectionChanged事件,并且也可能有多个侦听器。

使用反射订阅的事件未触发

你的问题缺少了一些东西。下面的完整程序演示了如何调用CollectionChanged事件。

using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
namespace ScratchConsole
{
    static class Program
    {
        private static void Main(string[] args)
        {
            Test<int>();
        }
        private static void Test<T>()
        {
            var listProperty = typeof(WebserviceUtil).GetProperty("List" + typeof(T).Name);
            var mainList = (ObservableCollection<T>)listProperty.GetValue(WebserviceUtil.Instance, null);
            mainList.CollectionChanged += AllItems_CollectionChanged;
            mainList.Add(default(T));
        }
        private static void AllItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Debug.WriteLine("AllItems_CollectionChanged was called!");
        }
        private class WebserviceUtil
        {
            public static readonly WebserviceUtil Instance = new WebserviceUtil();
            private WebserviceUtil() { ListInt32 = new ObservableCollection<int>(); }
            public ObservableCollection<int> ListInt32 { get; private set; }
        }
    }
}