C# - Singleton模式 [英] C# - Singleton Pattern
问题描述
你可以从我的昵称看到我其实新手学习Singleton模式,在那里我得到了一个问题。之前我已经了解到,静态构造函数是标准的构造函数之前,请务必执行,但是在下面这段代码,结果是不同的,我第一次看到的Insta字符串,然后静态,它为什么会发生?
密封类辛格尔顿
{
私人静态只读Singleton实例;
私人辛格尔顿()
{
Console.WriteLine(的Insta);
}
静态辛格尔顿()
{
实例=新辛格尔顿();
Console.WriteLine(静态);
}
公共静态Singleton实例
{
得到
{
返回实例;
}
}
}
类节目
{
静态无效的主要()
{
辛格尔顿S1 = Singleton.Instance;
}
}
如果你会写
静态辛格尔顿()
{
控制台。的WriteLine(静态); //这是第一位的
实例=新辛格尔顿();
}
你会看到你所期望的。
静态构造函数是在第一次执行,符合市场预期,但在打印控制台上的之后的的
实例=新辛格尔顿();
行,但此行执行的实例构造函数,所以出师表。
所以执行流程:
- 静态构造函数
-
实例=新辛格尔顿();
- 实例构造函数打印斯塔李>
- 实例构造函数打印斯塔李>
- 静态
-
As you can see from my nickname I'm newbie actually learning about Singleton pattern, where I got one problem. Before I've learned that static constructors are always executed before the standard constructors, but in this code below, the result is different, first I see the "Insta" string then the "Static", why does it happen ?
sealed class Singleton
{
private static readonly Singleton instance;
private Singleton()
{
Console.WriteLine("Insta");
}
static Singleton()
{
instance = new Singleton();
Console.WriteLine("Static");
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
class Program
{
static void Main()
{
Singleton s1 = Singleton.Instance;
}
}
If you will write
static Singleton()
{
Console.WriteLine("Static"); //THIS COMES FIRST
instance = new Singleton();
}
you would see what you expect
static ctor is executed at first, as expected, but you print on console after the
instance = new Singleton();
line, but this line execute instance ctor, so "inst".
So execution flow:
- static ctor
instance = new Singleton();
- instance ctor prints "insta"
- "static"
这篇关于C# - Singleton模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!