如何将事件传递给方法? [英] How to pass an event to a method?

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

问题描述

我想创建一个方法,该方法将事件作为参数并向其添加 eventHandler 以正确处理它.像这样:

I would like to create a method that takes an event as an argument and adds eventHandler to it to handle it properly. Like this:

我有两个事件:

public event EventHandler Click;
public event EventHandler Click2;

现在我想像这样(伪代码)将特定事件传递给我的方法:

Now I would like to pass a particular event to my method like this (pseudocode):

public AttachToHandleEvent(EventHandler MyEvent)
{
    MyEvent += Item_Click;
}

private void Item_Click(object sender, EventArgs e)
{
    MessageBox.Show("lalala");
}

ToolStripMenuItem tool = new ToolStripMenuItem();
AttachToHandleEvent(tool.Click);

有可能吗?

我注意到这段代码运行良好,然后返回到我的项目并注意到当我传递在我的类中声明的事件时它可以工作,但是当我传递来自其他类的事件时它仍然不起作用.

I've noticed that this code worked fine, and returned to my project and noticed that when I pass an event declared in my class, it works, but when I pass event from other class it still does not work.

我得到的是这个错误:

事件'System.Windows.Forms.ToolStripItem.Click'只能出现在左侧+= 或 -=

The event 'System.Windows.Forms.ToolStripItem.Click' can only appear on the left hand side of += or -=

推荐答案

我最初的回答适用于定义事件的班级内部,但您已经更新了您的问题以反映您希望从外部完成此定义类,所以我已经击中了.

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.

只有定义事件的类才能引用事件使用的隐式委托变量.在该类之外,您只能通过 +=-= 访问 addremove 方法.这意味着您不能直接执行您的要求.但是,您可以使用函数式方法.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆