事件订阅使用反射而不是触发

时间:2013-06-14 15:20:25

标签: c# .net events reflection

我有这段代码:

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; }

而我确实希望避免(un)手动订阅他们的CollectionChanged事件,并且可能还有几个听众。

1 个答案:

答案 0 :(得分:3)

您的问题中缺少某些内容。以下完整程序演示了调用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; }
        }
    }
}