public class Singleton
{
//private static bool instance_flag=false;instance flag 沒用了,直接判斷instance是否有實例就可以解決這個問題了.
private static Singleton instance;
public string name;
private Singleton()//將singleton函數變為private,防止直接調用new來創建它.
{
name="guqi";
Console.WriteLine("你只可以看到我一次哦");
}
public static Singleton GetInstance()
{
if (instance==null)
{
//instance_flag=true;
instance=new Singleton();
return instance;
}
else return instance;
}
}
謝謝vb1980對代碼的改進.
public static Singleton GetInstance()
{
if (instance==null)
{
instance=new Singleton();
}
return instance;
}
簡單許多.