有三个类,SingletonCounter、Test、Singleton,里面都包含了静态变量,SingletonCounter、Test结构差不多,Singleton包含了静态构造函数,静态属性等,将三个类的行都打上断点(需要断点的行有注释——加断点调试),当调试的时候,为什么总是最后执行到SingletonCounter的静态变量instance上???
测试了很多,和Singleton类的静态构造函数有关,望指点一二,谢谢!!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _04_Singleton3
{
class Program
{
[STAThread]
static void Main()
{//加断点调试
var temp = Singleton.Instance;
var str = Test.str;
for (int i = 0; i < 20; i++)
{
Console.WriteLine("Next singleton value: {0}", SingletonCounter.Instance.NextValue());
}
Console.ReadKey();
}
}
//1、sealed 类
sealed class SingletonCounter
{
private int Count = 0;//加断点调试
//2、私有构造函数
private SingletonCounter()
{//加断点调试
}
//3、公开静态实例对象
public static readonly SingletonCounter Instance = new SingletonCounter();//加断点调试
public long NextValue()
{
return ++Count;
}
}
sealed class Test
{
private int count = 0;//加断点调试
public static string str = "aaa";//加断点调试
public static readonly Test Instance = new Test();//加断点调试
}
sealed class Singleton
{
private static readonly Singleton instance = new Singleton();//加断点调试
static Singleton()
{//加断点调试
}
private Singleton()
{//加断点调试
}
public static Singleton Instance//加断点调试
{
get
{
return instance;
}
}
/*
*
*
*
*
*
*/
}
}