2016-02-28 44 views
0

在C#上工作。爲什麼委派事件的通用方法不適用於錯誤消息方法名稱預期

我的委託和事件是波紋管

#region delegate event 

     #region 
     public delegate void NotifynextDeviceReceivedDelegate(CustomEventArgs customEventArgs); 
     public event NotifynextDeviceReceivedDelegate NotifynextDeviceReceivedEvent; 
     #endregion 

     #region 
     public delegate void NotifynextDeviceedDelegate(CustomEventArgs customEventArgs); 
     public event NotifynextDeviceedDelegate NotifynextDeviceedEvent; 
     #endregion 

     #region 
     public delegate void NotifynextReceiveddDelegate(CustomEventArgs customEventArgs); 
     public event NotifynextReceiveddDelegate NotifynextReceiveddEvent; 
     #endregion 

     #endregion 

要調用我用波紋管語法,它的工作完美

   if (NotifynextDeviceReceivedEvent != null) 
        { 
         CustomEventArgs customEventArgs = new CustomEventArgs(receivedMessage, receivedTopic); 
         //Raise Event. All the listeners of this event will get a call. 
         NotifynextDeviceReceivedEvent(customEventArgs); 
        } 

需要寫相同的上述語法所有事件委託的所以,我決定編寫一般事件來調用它們,如下圖:

 InvokeEvents<NotifynextDeviceReceivedDelegate>(receivedMessage,receivedTopic,NotifynextDeviceReceivedEvent) 


     public static InvokeEvents<T>(string receivedMessage,string receivedTopic, T notifynextDeviceReceivedEvent) 
      { 

        if (notifynextDeviceReceivedEvent != null) 
        { 
         CustomEventArgs customEventArgs = new CustomEventArgs(receivedMessage, receivedTopic); 

         notifynextDeviceReceivedEvent(customEventArgs);//here is the problem show me error message 
        } 

      } 

InvokeEvents方法爲什麼notifynextDeviceReceivedEvent告訴我錯誤方法名稱預計

+0

[mcve]在這裏非常有幫助,因此我們可以將您的代碼複製/粘貼到IDE中,並查看您看到的完全相同的錯誤。 –

回答

0

你可以寫你的代碼,因爲這:

private static void InvokeEvents<T>(string receivedMessage, string receivedTopic, T eventDelegate) 
{ 
    if (eventDelegate != null) 
    { 
     var customEventArgs = new CustomEventArgs(receivedMessage, receivedTopic); 
     ((Delegate)(object)eventDelegate).DynamicInvoke(customEventArgs); 
    } 
} 

這工作。我測試了它。

您確實需要雙擊才能讓編譯器感到滿意。

製作存取器public也沒有意義,因爲您無法從類之外的任何地方將事件委託傳遞給它。

所以,因爲你不能從你的類之外的所有代碼,你再要你的類中編寫代碼來調用InvokeEvents,像這樣:

public void OnNotifynextDeviceedEvent() 
{ 
    InvokeEvents("", "", this.NotifynextDeviceedEvent); 
} 

這真的那麼意味着你可以有重複代碼在任何情況下。現在

,用C#6的語法,那麼你可以寫這些方法是這樣的:

public void OnNotifynextDeviceedEvent() 
    => this.NotifynextDeviceedEvent?.Invoke(new CustomEventArgs("", "")); 

所以,你真的不節省了大量的代碼 - 沒有 - 事實上,你正在創建一個弱類型方法。你真的應該堅持基本的方法。

相關問題