无法更改事件处理程序

时间:2015-02-13 02:56:49

标签: c# events event-handling bots irc

我的irc机器人,我正在尝试将消息接收器事件更改为链接到我其他类中的方法。

 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");
    }

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

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

这是我希望在收到消息时执行的不同类中的方法。

感谢您的帮助和对不起,如果这是一个非常愚蠢的问题,我对这一切仍然很陌生。

1 个答案:

答案 0 :(得分:0)

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

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

选项#1:

公开"加入"事件,以便第二类可以收到相同的通知并订阅频道的事件:

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:

公开收到的&#34;消息&#34;事件代替:

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

从您的帖子中不清楚原始事件的发件人是否重要。如果是,则恕我直言Option #1更好,因为它提供对事件的直接访问。但是,您可以修改Option #2,以便将sender传递给处理程序(Channel_MessageReceived()),而不是示例中的null({ {1}}更适合null,但不是强制性的。

如果这些选项都不适合您,请提供更好的背景信息。请参阅https://stackoverflow.com/help/mcvehttps://stackoverflow.com/help/how-to-ask