更改事件处理程序时遇到问题

Having trouble changing event handler

它适用于我的 irc 机器人,我正在尝试更改消息接收器事件以链接到我的另一个 class.

中的方法
 private static void client_Connected(object sender, EventArgs e)
    {


            gamebot.LocalUser.JoinedChannel += LocalUser_JoinedChannel;
            gamebot.LocalUser.MessageReceived += LocalUser_MessageReceived;


    }

   // private static void newmessage(object sender, IrcChannelEventArgs e)
   // {
   //     e.Channel.MessageReceived += Hangman.MessageReceivedHangman;

  //  }
    private static void LocalUser_JoinedChannel(object sender, IrcChannelEventArgs e)
    {
        e.Channel.MessageReceived += Channel_MessageReceived;
        Console.WriteLine("Joined " + e.Channel + "\n");
    }

只是不确定如何在方法之外获取通道事件参数,因此我可以更改事件。评论的方法显示了我需要的东西。

public static void MessageReceivedHangman(object sender, IrcMessageEventArgs e)
    {

这是另一个方法 class 我想在收到消息时执行。

感谢您的帮助,抱歉,如果这是一个非常愚蠢的问题,我对这一切还很陌生。

很难知道什么是最好的,因为你提供的上下文太少了。我们真正知道的是,您有一个 class(称为 class A)处理特定事件,而另一个 class(称为 class B)希望能够处理第一个 class 已经知道的事件。

基于此,至少有几种可能对您有用。

选项#1:

公开 "joined" 事件,以便第二个 class 可以接收相同的通知并订阅频道的事件:

class JoinedChannelEventArgs : EventArgs
{
    public Channel Channel { get; private set; }

    public JoinedChannelEventArgs(Channel channel) { Channel = channel; }
}

class A
{
    public static event EventHandler<JoinedChannelEventArgs> JoinedChannel;

    private static void LocalUser_JoinedChannel(object sender, IrcChannelEventArgs e)
    {
        e.Channel.MessageReceived += Channel_MessageReceived;
        Console.WriteLine("Joined " + e.Channel + "\n");

        EventHandler<JoinedChannelEventArgs> handler = JoinedChannel;

        if (handler != null)
        {
            handler(null, new JoinedChannelEventArgs(e.Channel);
        }
    }
}

class B
{
    static void SomeMethod()
    {
        A.JoinedChannel += A_JoinedChannel;
    }

    private static void A_JoinedChannel(object sender, JoinedChannelEventArgs e)
    {
        e.Channel += MessageReceivedHangman;
    }
}

选项#2:

公开 "message received" 事件:

class A
{
    public static event EventHandler<IrcMessageEventArgs> AnyChannelMessageReceived;

    public static void Channel_MessageReceived(object sender, IrcMessageEventArgs e)
    {
        // Whatever other code you had here, would remain

        EventHandler<IrcMessageEventArgs> handler = AnyChannelMessageReceived;

        if (handler != null)
        {
            handler(null, e);
        }
    }
}

class B
{
    static void SomeMethod()
    {
        A.AnyChannelMessageReceived += MessageReceivedHangman;
    }
}

从您的 post 中不清楚原始事件的发送者是否重要。如果是,那么恕我直言 Option #1 更好,因为它提供了对事件的直接访问。但是,您可以修改 Option #2,使其将 sender 传递给处理程序(在 Channel_MessageReceived() 中),而不是示例中的 nullnull对于 static event 来说更惯用,但不是强制性的)。

如果这些选项都不适合您,请提供更好的上下文。参见 https://whosebug.com/help/mcve and https://whosebug.com/help/how-to-ask