[英]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.