单身 - 我可以创建多个实例

Dav*_*ave 2 c# singleton design-patterns

我认为单身人士的观点是我一次只能初始化一个实例?如果这是正确的,那么我必须在我的C#控制台应用程序代码中出错(见下文).

如果我对单身人士的理解是正确的,或者我的代码中有错误,请有人告诉我.

using System;
using System.Collections.Generic;
using System.Text;

namespace TestSingleton
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton t = Singleton.Instance;
            t.MyProperty = "Hi";

            Singleton t2 = Singleton.Instance;
            t2.MyProperty = "Hello";

            if (t.MyProperty != "")
                Console.WriteLine("No");

            if (t2.MyProperty != "")
                Console.WriteLine("No 2");

            Console.ReadKey();
        }
    }

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

        public string MyProperty { get; set; }

        private Singleton()
        {}

        static Singleton()
        { }

        public static Singleton Instance { get { return instance; } }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tig*_*ran 8

事实上,这里只有一个实例.你得到2个指针

Singleton t = Singleton.Instance; //FIRST POINTER
t.MyProperty = "Hi";

Singleton t2 = Singleton.Instance; //SECOND POINTER
t2.MyProperty = "Hello";
Run Code Online (Sandbox Code Playgroud)

但他们都指向相同的内存位置.