类型

时间:2016-07-14 11:48:39

标签: c# events weakeventmanager

我有以下异常

  

未处理的类型' System.ArgumentException'发生在WindowsBase.dll

中      

其他信息:'活动'在类型' ConsoleApplication.ITest'。

上找不到事件

在这个复制品中:

using System.Windows; // add reference to WindowsBase

interface IBase
{
    event EventHandler Event;
}

interface ITest : IBase { }

class Test : ITest
{
    public event EventHandler Event;
}

class Program
{
    static void Main(string[] args)
    {
        var test = new Test();
        WeakEventManager<IBase, EventArgs>.AddHandler(test, "Event", (s, e) => { }); // works
        WeakEventManager<ITest, EventArgs>.AddHandler(test, "Event", (s, e) => { }); // exception
    }
}

为什么继承通过接口事件无法找到?从this method抛出异常。

1 个答案:

答案 0 :(得分:4)

我尝试了各种关于你的例子的组合。这里是唯一可用的代码。您似乎需要知道在继承层次结构中特定定义事件的位置。

using System.Reflection;
using MS.Internal.WindowsBase;

namespace EventTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new Test();
            WeakEventManager<IBase, EventArgs>.AddHandler(test, "IBaseEvent", (s, e) => { }); // works
            WeakEventManager<ITest, EventArgs>.AddHandler(test, "ITestEvent", (s, e) => { }); // works 
            WeakEventManager<Test, EventArgs>.AddHandler(test, "TestEvent", (s, e) => { }); // works
        }
    }
    interface IBase
    {
        event EventHandler IBaseEvent;
    }

    interface ITest : IBase { event EventHandler ITestEvent; }

    class Test : ITest
    {        
        public event EventHandler IBaseEvent;
        public event EventHandler ITestEvent;
        public event EventHandler TestEvent;
    }
}

到目前为止的整个组合;

            WeakEventManager<IBase, EventArgs>.AddHandler(test, "IBaseEvent", (s, e) => { }); // works
            WeakEventManager<IBase, EventArgs>.AddHandler(test, "ITestEvent", (s, e) => { }); // exception 
            WeakEventManager<IBase, EventArgs>.AddHandler(test, "TestEvent", (s, e) => { }); // exception

            WeakEventManager<ITest, EventArgs>.AddHandler(test, "IBaseEvent", (s, e) => { }); // exception
            WeakEventManager<ITest, EventArgs>.AddHandler(test, "ITestEvent", (s, e) => { }); // works 
            WeakEventManager<ITest, EventArgs>.AddHandler(test, "TestEvent", (s, e) => { }); // exception

            WeakEventManager<Test, EventArgs>.AddHandler(test, "IBaseEvent", (s, e) => { }); // exception
            WeakEventManager<Test, EventArgs>.AddHandler(test, "ITestEvent", (s, e) => { }); // exception 
            WeakEventManager<Test, EventArgs>.AddHandler(test, "TestEvent", (s, e) => { }); // works