我写了一个单例代码,我相信它不应该工作。它可能觉得它是低级问题,但它会帮助我理解。 如果不值得在这里发帖,任何人都可以检查和appolgy。
正在创建两个实例。为什么?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SingletonTest
{
public sealed class Test
{
private static readonly Test instance = new Test();
static Test()
{
}
private Test()
{
}
public static Test Instance
{
get
{
return instance;
}
}
public string Message { get; set; }
}
class Program
{
static void Main(string[] args)
{
var singletonSampleClass = Test.Instance;
singletonSampleClass.Message = "Hello";
Console.WriteLine("Singleton class usage: " + singletonSampleClass.Message);
var singletonSampleClass2 = Test.Instance;
singletonSampleClass2.Message = "Hello1";
Console.WriteLine("Singleton class usage: " + singletonSampleClass2.Message);
Console.Read();
}
}
}
由于 提前。
答案 0 :(得分:0)
试试这个:
var singletonSampleClass = Test.Instance; //First reference
singletonSampleClass.Message = "First Change";
Console.WriteLine("Singleton class usage: " + singletonSampleClass.Message);
// Expected to be "Singleton class usage: First Change"
var singletonSampleClass2 = Test.Instance; //Second reference
Console.WriteLine("Singleton class usage: " + singletonSampleClass2.Message);
// Expected to be "Singleton class usage: First Change" aka you have the same instance
singletonSampleClass2.Message = "Second Change";
Console.WriteLine("Singleton class usage: " + singletonSampleClass.Message); //use the first reference
// Expected to be "Singleton class usage: Second Change" even though you changed the instance with the second reference
Console.Read();
你会发现你只有一个实例......你的例子中有2个引用但仍然只有1个实例