简体   繁体   English

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

[英]Singleton - I can create multiple instances

I thought the point of a singleton was I could only initialize one instance at a time? 我认为单身人士的观点是我一次只能初始化一个实例? If this is correct, then I must have a fault in my C# console application code (see below). 如果这是正确的,那么我必须在我的C#控制台应用程序代码中出错(见下文)。

Would some one please be kind enough to inform me if my understanding of a singleton is correct or if there is an error in my code. 如果我对单身人士的理解是正确的,或者我的代码中有错误,请有人告诉我。

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; } }
    }
}

Infact you have only one instance here. 事实上,这里只有一个实例。 You get 2 pointers 你得到2个指针

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

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

But they both are pointing to the same memory location. 但他们都指向相同的内存位置。

Try 尝试

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

Just tested your code and it gives Hello Hello and not Hi Hello . 刚刚测试了你的代码,它给Hello Hello而不是Hi Hello So you were manipulating the same instance 所以你在操纵同一个实例

Actually you have only one instance in your sample program. 实际上,您的示例程序中只有一个实例。 The variables t1 and t2 point to the very same instance of the object. 变量t1和t2指向对象的同一实例。 The object you created is 您创建的对象是

private static readonly Singleton instance = new Singleton();

And both t1 and t2 point to the same object. 并且t1和t2都指向同一个对象。 As said by someone else in memory there is just one object created. 正如内存中的其他人所说,只创建了一个对象。

Your reference to Singleton.Instance; 您对Singleton.Instance; 引用 Singleton.Instance; is a reference to Singleton.instance and so a reffence to one single object. 是对Singleton.instance的引用,因此对单个对象的依赖。 There is no creation of a second Singleton object 没有创建第二个Singleton 对象

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

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