转发不同类型的事件 [英] Forwarding Events of Different Type

查看:86
本文介绍了转发不同类型的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将事件从一个类转发到其中包含的对象(如此处所述:在C#中转发事件)。但是,事件的类型不同。

I'm trying to forward events from one class to objects contained within it (as described here: Forwarding events in C#). However, the events are of different type.

例如,我有一个类 Item ,它公开了一个 ValueChanged 类型为 EventHandler 的事件处理程序。类 ItemHaver 公开了 EventHandler< StatusEventArgs> ,只要 Item.ValueChanged 可以,但是还应该提供其他信息。如何正确地对 ItemValueChanged 事件声明实现添加/删除

For example, I have a class Item which exposes a ValueChanged event handler of type EventHandler. The class ItemHaver exposes an EventHandler<StatusEventArgs>, which should fire whenever Item.ValueChanged does, but should also provide additional information. How do I properly implement add/remove to the ItemValueChanged event declaration?

在下面的代码中, add 方法中的lambda函数是否将执行正确的操作,如果是,则处理<$ c的正确方法是什么? $ c>删除?

In the below code, would the lambda function in the add method perform the correct action, and if so, what's the proper way to handle the remove?

class Item
{
    public event EventHandler ValueChanged;
}

class ItemHaver
{
    private int _status;
    private Item _item;

    public event EventHandler<StatusEventArgs> ItemValueChanged
    {
        add 
        { 
            _item.ValueChanged += value; // Wrong type
            _item.ValueChanged += 
                (obj, e) => value(obj, new StatusEventArgs(this._status));
        }
        remove 
        { 
            _item.ValueChanged -= // Does this even work?
                (obj, e) => value(obj, new StatusEventArgs(this._status));  
        }
    }
}

class StatusEventArgs : EventArgs
{
    int Status { get; private set; }
    StatusEventArgs(int status) { Status = status; }
}


推荐答案

我会尝试使用

class ItemHaver
{
    private int _status;
    private Item _item;

    private Dictionary<EventHandler<StatusEventArgs>, EventHandler> handlersMap = new Dictionary<EventHandler<StatusEventArgs>, EventHandler>();

    public event EventHandler<StatusEventArgs> ItemValueChanged
    {
        add
        {
            // _item.ValueChanged += value; // Wrong type
            handlersMap.Add(value, (obj, e) => value(obj, new StatusEventArgs(this._status)));
            _item.ValueChanged += handlersMap[value];
        }
        remove
        {
            _item.ValueChanged -= handlersMap[value];
        }
    }
}

这篇关于转发不同类型的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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