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;
}
简单许多.
本文地址:http://com.8s8s.com/it/it42330.htm