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

问题描述 投票:0回答:1

它适用于我的 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");
    }

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

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

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

c# events event-handling bots irc
1个回答
0
投票

很难知道什么是最好的,因为你提供的背景信息太少了。我们真正知道的是,您有一个类(称为

class A
)处理特定事件,另一个类(称为
class B
)希望能够处理第一个类已经知道的事件。

基于此,至少有几种可能适合您。

选项#1:

暴露“joined”事件,以便第二个类可以接收相同的通知并订阅频道的事件:

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:

改为公开“消息已收到”事件:

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
null
对于
static event
来说更惯用,但是非强制)。

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

© www.soinside.com 2019 - 2024. All rights reserved.