gpt4 book ai didi

C# 如何创建一个发布事件和订阅类的单例?

转载 作者:行者123 更新时间:2023-12-02 05:10:37 29 4
gpt4 key购买 nike

目标让一个单例发布事件并允许任何类订阅/收听这些事件

问题:我不知道该怎么做。下面的代码是非法的,但它提供了我正在尝试做的事情

TransmitManager 类 - 发布者

    //Singleton
public sealed class TransmitManager
{

delegate void TransmitManagerEventHandler(object sender);
public static event TransmitManagerEventHandler OnTrafficSendingActive;
public static event TransmitManagerEventHandler OnTrafficSendingInactive;

private static TransmitManager instance = new TransmitManager();



//Singleton
private TransmitManager()
{

}

public static TransmitManager getInstance()
{
return instance;
}

public void Send()
{
//Invoke Event
if (OnTrafficSendingActive != null)
OnTrafficSendingActive(this);

//Code connects & sends data

//Invoke idle event
if (OnTrafficSendingInactive != null)
OnTrafficSendingInactive(this);

}
}

测试类 - 事件订阅者

   public class Test
{

TrasnmitManager tm = TransmitManager.getInstance();

public Test()
{
//I can't do this below. What should my access level be to able to do this??

tm.OnTrafficSendingActive += new TransmitManagerEventHandler(sendActiveMethod);

}

public void sendActiveMethod(object sender)
{

//do stuff to notify Test class a "send" event happend
}
}

最佳答案

您不需要将事件设为静态

public event TransmitManagerEventHandler OnTrafficSendingActive;
public event TransmitManagerEventHandler OnTrafficSendingInactive;

关于C# 如何创建一个发布事件和订阅类的单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15526331/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com