为什么委托事件的通用方法不起作用,错误消息方法名称需要

本文关键字:方法 消息 错误 不起作用 事件 为什么 | 更新日期: 2023-09-27 18:36:30

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

调用事件方法中,为什么通知下一个设备接收事件显示错误 方法名称应达到预期

为什么委托事件的通用方法不起作用,错误消息方法名称需要

你可以这样写代码:

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("", ""));

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