悬赏园豆:5
[已关闭问题]
<P>先看段可行的代码:</P>
<P>using System;</P>
<P>class Singleton<BR>{<BR> private int use = 0;<BR> private int x; <BR> private int y;<BR> private static Singleton []instance;<BR> private static object lockHelp = new Object();<BR> private static int size;<BR> private Singleton()<BR> {}<BR> public static void Init(int x)<BR> {<BR> size = x;<BR> instance = new Singleton[size];<BR> }</P>
<P> public static Singleton getInstance()<BR> {<BR> if(instance == null)<BR> {<BR> lock(lockHelp)<BR> {<BR> if(instance == null)<BR> {<BR> instance = new Singleton[10];<BR> }<BR> }<BR> <BR> }<BR> for(int i = 0; i < size; i++)<BR> {<BR> lock(lockHelp)<BR> {<BR> if(instance[i] == null)<BR> {<BR> instance[i] = new Singleton();<BR> instance[i].use = 1;<BR> return instance[i];<BR> }<BR> else<BR> {<BR> if(instance[i].use == 0)<BR> {<BR> instance[i].use = 1;<BR> return instance[i];<BR> }<BR> }<BR> }<BR> }<BR> return null;<BR> }<BR> public int X<BR> {<BR> get<BR> { return x; }<BR> set<BR> { x = value; }<BR> }<BR> public int Y<BR> {<BR> get<BR> { return y; }<BR> set<BR> { y = value; }<BR> }<BR> public void dayin()<BR> {<BR> Console.WriteLine("这个实例的X为{0},Y为{1},使用计数为{2}", x, y, use);<BR> <BR> }<BR> public static void del(Singleton s)<BR> {<BR> for(int i = 0; i < size; i++)<BR> {<BR> if(instance[i] == s)<BR> {<BR> s = instance[i] = null;<BR> break;<BR> }<BR> }<BR> }<BR>}</P>
<P><BR>class Test<BR>{<BR> public static void Main()<BR> {<BR> Singleton.Init(10);<BR> Sin
问题补充:
class Test
{
public static void Main()
{
Singleton.Init(10);
Singleton s1 = Singleton.getInstance();
s1.X = 3;
s1.dayin();
Singleton s2 = Singleton.getInstance();
s2.dayin();
Singleton s3 = Singleton.getInstance();
s3.dayin();
Singleton s4 = Singleton.getInstance();
s4.dayin();
Singleton s5 = Singleton.getInstance();
s5.dayin();
Singleton s6 = Singleton.getInstance();
s6.dayin();
Singleton s7 = Singleton.getInstance();
s7.dayin();
Singleton s8 = Singleton.getInstance();
s8.dayin();
Singleton s9 = Singleton.getInstance();
s9.dayin();
Singleton s10 = Singleton.getInstance();
s10.dayin();
Singleton.del(s4);
Singleton s11 = Singleton.getInstance();
s11.dayin();
Console.ReadLine();
}
}
这样删除一个对象池中的对象有点麻烦,我希望直接设置 s1 = null;这一句话就OK
所以将函数改为:public static void getInstance(ref Singleton s)
外面:
public static void Main()
{
Singleton.Init(10);
Singleton s = null;
Singleton.getInstance(ref s);
s.dayin();
}
但出现未将对象的引用设置到对象的实例的错误
修改后的方法:
public static void getInstance(ref Singleton s)
{
if(instance == null)
{
lock(lockHelp)
{
if(instance == null)
{
instance = new Singleton[10];
}
}
}
for(int i = 0; i < size; i++)
{
lock(lockHelp)
{
if(instance[i] == null)
{
instance[i] = new Singleton();
instance[i].use = 1;
s = instance[i];
}
else
{
if(instance[i].use == 0)
{
instance[i].use = 1;
s = instance[i];
}
}
}
}
s = null;
}