在类型上找不到事件

本文关键字:事件 找不到 类型 | 更新日期: 2023-09-27 17:56:51

我有以下异常

WindowsBase 中发生了类型为"System.ArgumentException"的未处理异常.dll

其他信息:"事件"事件"

事件在类型"控制台应用程序.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
    }
}

为什么找不到通过接口继承的事件?此方法引发异常。

在类型上找不到事件

我已经尝试了关于您的示例的各种组合。这是这里唯一的工作代码。您似乎需要知道事件在继承层次结构中专门定义的位置。

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