为什么委托事件的通用方法不能使用错误消息预期的方法名称

时间:2016-02-28 04:53:33

标签: c# .net generics delegates

使用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显示错误预期的方法名称

1 个答案:

答案 0 :(得分: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("", ""));

所以你真的没有保存太多的代码 - 实际上没有 - 并且你正在创建一个弱类型的方法。你真的应该坚持基本方法。