在應用程式代碼内執行個體化一個類或結構時,隻要有代碼引用它,就會形成強引用。例如,如果有一個類myclass(),并建立一個變量myclassvariable來引用該類的對象,那麼隻要在
myclassvariable在作用域内,就存在對myclass()的強引用,如下所示:
myclass() myclassvariable=new myclass();
這意味設垃圾回收器不會清除myclass對象時用的記憶體。一般而言這是好事,因為可能需要通路myclass對象,但是如果myclass對象過大,而又不經常對myclass通路,此時就需要建立對象的弱引用。
static void main(string[]
args)
{
weakreference mathrefance = new weakreference(new
mathtest());//聲明弱引用
mathtest
math;
math
= mathrefance.target as
mathtest;//target屬性傳回的是object類型,是以必須轉換成mathtest類型。
if (math !=
null)
math.value =
30;
console.writeline(math.value);
console.writeline(math.getsquare());
}
else
console.writeline("not
referance");
gc.collect();
if
(mathrefance.isalive)//要想使用,先檢查對象沒有被gc回收,isalive就是做這個工作的
math = mathrefance.target as
mathtest;
console.writeline("referance is not
available");
console.readkey();
}
//測試用的類,此類并不是最好的設計,隻是作為例子運用;如得到pi的值,一般在類中聲明為(const)常量。
class mathtest
public int
value;
getsquare()//執行個體方法得到value的平方。
return
value * value;
public static int
getsquareof(int x)//靜态方法得到x的平方。
return x
* x;
public static double
getpi()//靜态方法得到pi的值
3.1415926;
}
輸出為:30
900