如何创建一个类只能在C#中的单个实例创建一个、实例、只能在

2023-09-06 06:09:34 作者:好了伤疤忘了疼

我不知道是否有一种机制或模式,允许类在C#中的一个实例。我已经听到了辛格尔顿类的,但我不知道如何使用它做好。

I wonder if there is a mechanism or pattern to allow only one instance of a class in C#. I have heard of the Singleton class, but i don't know how to use it well.

推荐答案

使用单,这是一类只允许创建其自身的一个实例。

Using singleton, that is a class which only allows a single instance of itself to be created.

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

这种模式的操作简单,可以减少到以下内容:

The operation of this pattern is simple and could be reduced to the following:

隐藏Singleton类的构造函数,这样客户可以不被实例化。             要声明包含引用,我们处理的唯一实例的单例类的私有成员变量。             提供一流的辛格尔顿一个函数或属性,提供了访问一个由Singleton实例维护。

Hide the constructor of the Singleton class, so that clients may not be instantiated. To declare the Singleton class private member variable containing the reference to the unique instance that we handle. Provide in class Singleton a function or property that provides access to the one maintained by the Singleton instance.