本文介绍了如何通过一个事件的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个需要一个事件作为一个参数,并增加了事件处理程序,以它来正确地处理它的方法。像这样的:

我有两个事件:

 公共事件的EventHandler点击;
公共事件的EventHandler CLICK2;

现在我想一个特定的事件传递给我的方法是这样的(伪code):

 公共AttachToHandleEvent(事件处理MyEvent)
{
    MyEvent + = ITEM_CLICK;
}私人无效ITEM_CLICK(对象发件人,EventArgs的发送)
{
    的MessageBox.show(LALALA);
}ToolStripMenuItem工具=新ToolStripMenuItem();
AttachToHandleEvent(tool.Click);

这可能吗?

我注意到,这code正常工作,并返回到我的项目,并注意到,当我通过我的类中声明的事件,它的工作原理,但是当我通过从其他类的事件仍然无法正常工作

我得到的是这个错误:

解决方案

My original answer was suitable from within the class that defined the event, but you've since updated your question to reflect that you wish to accomplish this from outside the defining class, so I've stricken that.

Only the class that defines an event can refer to the implicit delegate variable that the event uses. From outside that class, you only have access to the add and remove methods, via += and -=. This means that you can't do what you're asking, directly. You can, however, use a functional approach.

class A{
    public event EventHandler Event1;

    public void TriggerEvent1(){
        if(Event1 != null)
            Event1(this, EventArgs.Empty);
    }
}

class B{
    static void HandleEvent(object o, EventArgs e){
        Console.WriteLine("Woo-hoo!");
    }

    static void AttachToEvent(Action<EventHandler> attach){
        attach(HandleEvent);
    }

    static void Main(){
        A a = new A();
        AttachToEvent(handler=>a.Event1 += handler);
        a.TriggerEvent1();
    }
}

这篇关于如何通过一个事件的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:01