声明一个类、怎么保证这个类只能有一个实例对象
可以用单例模式.
public class Singleton
{
private static Singleton instance;
private static readonly object obj = new object();
private Singleton()
{
}
//这里实例化
public static Singleton GetInstance()
{
if (instance == null)
{
lock (obj)//加锁
{
if (instance == null) //双重锁
instance = new Singleton();
}
}
return instance;
}
}
public class Singleton
{
private static Singleton instance;
private static readonly object obj = new object();
private Singleton()
{
}
//这里实例化
public static Singleton GetInstance()
{
if (instance == null)
{
lock (obj)//加锁
{
if (instance == null) //双重锁
instance = new Singleton();
}
}
return instance;
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答 2013-04-13
如果是普通类的话,使用全局变量对该类做一个引用计数,在类的构造中+1,如果遇到该数字已大于1,则抛出异常,在析构中-1。
第2个回答 2013-04-13
这个貌似不能吧,只能不给实例化的。
第3个回答 2013-04-13
等额头可能
第4个回答 2013-04-13
设计模式里面有一种可以实现。单例模式。具体问百度