转发在C#中的事件 [英] Forwarding events in C#

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

问题描述

我使用转发在C#中的事件的类。我想知道,如果有做
它需要较少的代码开销的一种方式。

I'm using a class that forwards events in C#. I was wondering if there's a way of doing it that requires less code overhead.

下面是一个什么样我到目前为止的例子。

Here's an example of what I have so far.

class A
{
   public event EventType EventA;
}

class B
{
   A m_A = new A();
   public event EventType EventB;

   public B()
   {
      m_A.EventA += OnEventA;
   }

   public void OnEventA()
   {
      if( EventB )
      {
         EventB();
      }
   }
}



A类引发原始事件。 B类转发它作为EventB(这是基本相同的事件)。一类是从其他模块隐藏所以不能直接订阅EventA。

Class A raises the original event. Class B forwards it as EventB (which is essentially the same event). Class A is hidden from other modules so they can't subscribe to EventA directly.

我试图做的是减少B类代码开销转发事件,因为通常有一个在B类的事件没有真正的处理我也会有几个不同的事件,所以它需要编写大量的OnEvent()的B类的方法只会转发的事件。

What I'm trying to do is reduce the code overhead in class B for forwarding the event, as typically there's no real handling of the events in class B. Also I'll have several different events so it would require writing a lot of OnEvent() methods in class B that only serve to forward the events.

时能够自动以某种方式链接到EventA EventB,所以我有这样的事情:

Is it possible to automatically link EventA to EventB in some way, so I'd have something like this:

class B
{
   A m_A = new A();
   public event EventType EventB;

   public B()
   {
      m_A.EventA += EventB; // EventA automatically raises EventB.
   }
}



我使用的是C#2.0编译器BTW。

I'm using a C# 2.0 compiler btw.

推荐答案

绝对:

class B
{
    private A m_a = new A();

    public event EventType EventB
    {
        add { m_a.EventA += value; }
        remove { m_a.EventA -= value; }
    }
}

在换句话说,Eve​​ntB订阅/取消订阅代码只传递订阅/退订上EventA请求。

In other words, the EventB subscription/unsubscription code just passes the subscription/unsubscription requests on to EventA.

请注意,这并不让你引发该事件的只是的为用户谁订阅到EventB,但是。这就像直接传递某人的地址到大众市场的公司,而你原来的方式更像是订阅大众营销公司自己,让人们问你发送邮件的副本给他们。

Note that this doesn't allow you to raise the event just for subscribers who subscribed to EventB, however. It's like passing someone's address directly onto a mass marketing company, whereas your original way is more like subscribing to the mass marketing company yourself, and allowing people to ask you to send copies of the mails to them.

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

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