日期:2014-05-19  浏览次数:20749 次

用C#实现一个类,要求该类只能被实例化一次,怎么写?谢谢
如题,万分感谢!

------解决方案--------------------
Singleton模式:
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}

------解决方案--------------------
也可以选择在调用的时候才实例化的

public class sealed Singleton
{
private static volatile Singleton _instance;
private static object syncRoot = new object();

private Singleton() { }

public Singleton Instance
{
get
{
if(_instance == null)
{
Lock(syncRoot)
{
if(_instance == null)
{
_instance = new Singleton();
}
}
}
return _instance;
}
}
}