大家帮我看看应该怎么理解才能正确的理解。他说可以创建唯一的实例。但是我在底下创建并进行比较的时候却没有得到的结果是想通的。。
类
public sealed class _Singleton_
{
static readonly _Singleton_ s = new _Singleton_();
static _Singleton_()
{
}
public _Singleton_()
{
}
public static _Singleton_ S
{
get
{
return s;
}
}
}
这里开始创建实例然后进行比较
_Singleton_ s = new _Singleton_();
_Singleton_ s1 = new _Singleton_();
if ( s.Equals(s1))
{
Response.Write("aaaaa");
}
你这不是单例模式,单例模式应当将构造函数设为private,仅允许通过访问_Singleton_S属性来获取对象
public sealed class _Singleton_
{
private _Singleton_ s;
private _Singleton_()
{
}
public static _Singleton_ S
{
get
{
if (s == null)
{
s = new _Singleton_();
}
return s;
}
}
}
class A
{
public void Test()
{
_Singleton_ s = _Singleton_.S;
_Singleton_ s1 = _Singleton_.S;
if (s.Equals(s1))
{
Response.Write("aaaaa");
}
}
}
很多,最简单的