如何传递一个事件,在C#中的函数? [英] How can I pass an event to a function in C#?

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

问题描述

我期待的事件传递给一个辅助函数。这个功能将一方法附加到该事件。然而,我无法正确地传递事件。我试图传递一个事件处理程序和LT; TEventArgs> 。它编译,但事件不附后(但仍然增加,似乎事件处理程序的副本是由)



例如,如果我有这样的:

 公共事件的EventHandler< EventArgs的> MyEvent; 

和辅助功能:

 公共静态无效MyHelperFunction< TEventArgs>(事件处理程序和LT; TEventArgs> eventToAttachTo)
{
eventToAttachTo + =(发件人,E)=> {Console.WriteLine(HELLO WORLD); };
}

和来电:

  MyHelperFunction(MyEvent); 
MyEvent(空,新的EventArgs()); // 什么也没做。


解决方案

为什么这不工作的原因是+ =当适用于委托创建一个新的委托这是旧的和新的组合。它不修改现有的委托。



在为了得到这个工作,你必须通过引用传递的委托。

 公共静态无效的助手(REF事件处理程序和LT; EventArgs的> E)
{
E + =(X, Y)=> {};
}



这个作品的方法之外的原因是因为在LHS仍是实际领域。所以,+ =将创建一个新的委托并指派回成员字段。


I am looking to pass an event to a helper function. This function will attach a method to the event. However, I am having trouble properly passing the event. I have tried passing a EventHandler<TEventArgs>. It compiles, but events are not attached (but are still added; it seems a copy of the event handler is made).

For example, if I have this:

public event EventHandler<EventArgs> MyEvent;

And the helper function:

public static void MyHelperFunction<TEventArgs>(EventHandler<TEventArgs> eventToAttachTo)
{
    eventToAttachTo += (sender, e) => { Console.WriteLine("Hello world"); };
}

And the caller:

MyHelperFunction(MyEvent);
MyEvent(null, new EventArgs()); // Does nothing.

解决方案

The reason why this does not work is += when applied to a delegate creates a new delegate which is the combination of the old and the new. It does not modify the existing delegate.

In order to get this to work you will have to pass the delegate by reference.

public static void Helper(ref EventHandler<EventArgs> e)
{
    e+= (x,y) => {};
}

The reason this works outside of the method is because the LHS is still the actual field. So += will create a new delegate and assign back to the member field.

这篇关于如何传递一个事件,在C#中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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