gpt4 book ai didi

c# - 如何确保只创建该类对象的一个​​实例?

转载 作者:行者123 更新时间:2023-11-30 14:10:49 26 4
gpt4 key购买 nike

在我的A类中,我有一个ZMQ对象

    public void StartLogging(object connection)
{
var ctxt = new ZMQ.Context();
var publisher = ctxt.Socket(ZMQ.SocketType.PUB);
publisher.Bind("tcp://127.0.0.1:5000");
if (connection is uint)
{
Console.WriteLine("strange");
Console.ReadLine();
}
}

B 类会做类似的事情

ClassA test=new ClassA();

C 类也会做同样的事情

ClassA test=new ClassA();

这将导致创建 2 个 ZMQ 对象绑定(bind)到同一个端口,这将导致错误。我该如何解决这个问题?

最佳答案

您需要的是单例。 Jon Skeet's excellent article会告诉你比你需要知道的更多。

在您的情况下,它可能看起来像这样:

public void StartLogging(object connection)
{
var ctxt = Singleton.Instance.Context();
var publisher = ctxt.Socket(ZMQ.SocketType.PUB);
publisher.Bind("tcp://127.0.0.1:5000");
if (connection is uint)
{
Console.WriteLine("strange");
Console.ReadLine();
}
}

public sealed class Singleton
{
private static readonly ZMQ instance = new ZMQ();

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}

private Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

关于c# - 如何确保只创建该类对象的一个​​实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22342085/

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