2013-03-20 78 views
2

目標:有一個單發佈活動,並允許任何類認購/聽那些事件C#如何創建一個發佈事件和類訂閱的單身人士?

問題:我無法弄清楚如何做到這一點。下面的代碼是非法的,但它purveys什麼,我試圖做

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 
    } 
    } 

回答

4

你不應該需要使事件static

public event TransmitManagerEventHandler OnTrafficSendingActive; 
public event TransmitManagerEventHandler OnTrafficSendingInactive; 
1

要麼你的事件必須是實例成員,要麼你必須將它們解決爲靜態。

TransmitManager.OnTrafficSendingActive +=... 

OR

public event TransmitManagerEventHandler OnTrafficSendingActive; 

... 

TransmitManager.Instance.OnTrafficSendingActive+=... 

另外:使用事件處理程序爲您的活動委託。考慮製作一個自定義參數類並將狀態傳遞給一個事件而不是多個事件。這也可以讓你傳遞狀態信息。