C#中單例形式的三種寫法示例。本站提示廣大學習愛好者:(C#中單例形式的三種寫法示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中單例形式的三種寫法示例正文
第一種最簡略,但沒有斟酌線程平安,在多線程時能夠會出成績,不外俺從沒看過失足的景象,表小看我……
public class Singleton
{
private static Singleton _instance = null;
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
第二種斟酌了線程平安,不外有點煩,但相對是正軌寫法,經典的一叉
public class Singleton
{
private volatile static Singleton _instance = null;
private static readonly object lockHelper = new object();
private Singleton(){}
public static Singleton CreateInstance()
{
if(_instance == null)
{
lock(lockHelper)
{
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
第三種能夠是C#如許的高等說話獨有的,其實懶得出奇
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
}
哦,shit!