将事件作为参数传递给方法 [英] Pass an event as a parameter to a method

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

问题描述


可能重复:

如何传递事件一个方法?

可以将事件作为参数传递给一种方法?

Is it possible to pass an event as a parameter to a method?

例如,以下方法订阅事件,确定工作并取消订阅事件:

For example, the following method subscribes to the event, does work, and unsubscribes from the event:

void SubscribeDoAndUnsubscribe<TElement, TEventArgs>(
        IEnumerable<TElement> elements,
        ??? elementEvent)
    where TEventArgs: EventArgs
{
    EventHandler<TEventArgs> handler = (sender, e) => { /* Handle an event */ };

    foreach (var element in elements)
    {
         // Subscribe somehow
         element.elementEvent += handler
    }

    // Do things

    foreach (var element in elements)
    {
         // Unsubscribe somehow
         element.elementEvent -= handler
    }
}

客户端代码:

var elements = new [] { new Button(), new Button() };
SubscribeDoAndUnsubscribe(elements, ??? /* e => e.Click */);

如果不可能,我如何以其他方式实现类似的逻辑?我会通过订阅/取消订阅方法的代表对吗?

If it's not possible, how do I achieve the similar logic in other ways? Shall I pass pair of delegates for subscribe/unsubscribe methods?

推荐答案

事实上,事实上,事实上发现事件不是一流在C#中您不能将事件作为数据传递。您可以通过委派代理将代理传递给与接收者相关联的方法作为第一类对象。您可以将作为(主要)第一类对象的引用传递给任何变量。 (我说主要是因为对变量的引用不能存储在字段中,存储在数组中等等;与其他类型的数据相比,它们受到高度限制)。您可以通过类型获取它的Type对象并传递给它。

You have in fact discovered that events are not "first class" in C#; you cannot pass around an event as data. You can pass around a delegate to a method associated with a receiver as a first-class object by making a delegate. You can pass around a reference to any variable as a (mostly) first-class object. (I say "mostly" because references to variables cannot be stored in fields, stored in arrays, and so on; they are highly restricted compared to other kinds of data.) You can pass around a type by obtaining its Type object and passing that around.

但是,没有办法直接传递一个与特定实例关联的事件,属性,索引器,构造函数或析构函数作为数据。你可以做的最好的就是按照你的建议,使一个代表(或一对代表)从一个lambda开始。或者,获取与事件相关联的反射对象,并将其传递给实例。

But there is no way to directly pass around as data an event, property, indexer, constructor or destructor associated with a particular instance. The best you can do is to make a delegate (or pair of delegates) out of a lambda, as you suggest. Or, obtain the reflection object associated with the event and pass that around, along with the instance.

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

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