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

use*_*315 3 c# class

在我的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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

B级会做类似的事情

ClassA test=new ClassA();
Run Code Online (Sandbox Code Playgroud)

C级也会做同样的事情

ClassA test=new ClassA();
Run Code Online (Sandbox Code Playgroud)

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

paq*_*mez 6

单身就是你需要的. Jon Skeet的精彩文章将告诉你比你需要知道的更多.

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

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)