下載app免費領取會員
class Program
{
static void Main(string[] args)
{
TestClass.Defalut.i = 5;
//輸出5
Console.WriteLine(TestClass.Defalut.i);
GC.Collect();
//輸出0,表示Default已經(jīng)是重新生成的,之前的對象已經(jīng)被回收
Console.WriteLine(TestClass.Defalut.i);
TestClass1.Defalut.i = 5;
//輸出5
Console.WriteLine(TestClass1.Defalut.i);
GC.Collect();
//輸出5
Console.WriteLine(TestClass1.Defalut.i);
Console.ReadLine();
}
}
public class TestClass
{
private static readonly object locker = new object();
private static WeakReference _defalut = null;
public static TestClass Defalut
{
get
{
if(_defalut==null||!_defalut.IsAlive)
{
lock(locker)
{
TestClass tc = new TestClass();
_defalut = new WeakReference(tc);
}
}
return _defalut.Target as TestClass;
}
}
private TestClass()
{
}
public int i = 0;
}
public class TestClass1
{
private static readonly object locker = new object();
private static TestClass1 _defalut = null;
public static TestClass1 Defalut
{
get
{
if (_defalut == null)
{
lock (locker)
{
_defalut = new TestClass1();
}
}
return _defalut;
}
}
private TestClass1()
{
}
public int i = 0;
}
本文版權(quán)歸腿腿教學網(wǎng)及原創(chuàng)作者所有,未經(jīng)授權(quán),謝絕轉(zhuǎn)載。