C#如何创建发布事件的Singleton&订阅的类?

时间:2013-03-20 14:27:25

标签: c# events event-handling

目标:拥有单例发布事件并允许任何类订阅/收听这些事件

问题:我无法弄清楚如何做到这一点。下面的代码是非法的,但它会告诉我正在尝试做的事情

TransmitManager类 - 发布者

    //Singleton
    public sealed class TransmitManager
    {

        delegate void TransmitManagerEventHandler(object sender);
        public static event TransmitManagerEventHandler OnTrafficSendingActive;
        public static event TransmitManagerEventHandler OnTrafficSendingInactive;

        private static TransmitManager instance = new TransmitManager();



        //Singleton
        private TransmitManager()
        {

        }

        public static TransmitManager getInstance()
        {
            return instance;
        }

        public void Send()
        {
           //Invoke Event
           if (OnTrafficSendingActive != null)
              OnTrafficSendingActive(this);

          //Code connects & sends data

          //Invoke idle event
          if (OnTrafficSendingInactive != null)
            OnTrafficSendingInactive(this);

       }
   }

测试类 - 活动订阅者

   public class Test
   {

     TrasnmitManager tm = TransmitManager.getInstance();

     public Test()
     {
        //I can't do this below. What should my access level be to able to do this??

        tm.OnTrafficSendingActive += new TransmitManagerEventHandler(sendActiveMethod);

     }

     public void sendActiveMethod(object sender)
     {

        //do stuff to notify Test class a "send" event happend
     }
  }

2 个答案:

答案 0 :(得分:4)

您不需要制作活动static

public event TransmitManagerEventHandler OnTrafficSendingActive;
public event TransmitManagerEventHandler OnTrafficSendingInactive;

答案 1 :(得分:1)

您的活动必须是实例成员,或者您必须将它们称为静态。

TransmitManager.OnTrafficSendingActive +=...

OR

public event TransmitManagerEventHandler OnTrafficSendingActive;

...

TransmitManager.Instance.OnTrafficSendingActive+=...

另外:使用EventHandler作为事件委托。考虑创建自定义参数类并将状态传递给一个事件而不是多个事件。这也可以让你传递状态信息。