How to create a class which can only have a single instance in C#

前端 未结 6 589
梦如初夏
梦如初夏 2020-12-19 08:09

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 we

6条回答
  •  有刺的猬
    2020-12-19 08:42

    Singleton is not a class, but rather a pattern. Here is an example:

    class Singleton {
        private Singleton() {}
    
        static private Singleton GetIt() {
            return theOne;
        }
    
        static private Singleton theOne = new Singleton();
    }
    

提交回复
热议问题