繁体   English   中英

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

[英]Singleton - I can create multiple instances

我认为单身人士的观点是我一次只能初始化一个实例? 如果这是正确的,那么我必须在我的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; } }
    }
}

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

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

Singleton t2 = Singleton.Instance; //SECOND POINTER
t2.MyProperty = "Hello";

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

尝试

Console.WriteLine("{0}, {1}", t.MyProperty, t2.MyProperty);

刚刚测试了你的代码,它给Hello Hello而不是Hi Hello 所以你在操纵同一个实例

实际上,您的示例程序中只有一个实例。 变量t1和t2指向对象的同一实例。 您创建的对象是

private static readonly Singleton instance = new Singleton();

并且t1和t2都指向同一个对象。 正如内存中的其他人所说,只创建了一个对象。

您对Singleton.Instance; 引用 Singleton.Instance; 是对Singleton.instance的引用,因此对单个对象的依赖。 没有创建第二个Singleton 对象

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM