WeakReference 弱引用

弱引用是使用WeakReference类创建的.因为对象可能在任意时刻被回收,所以在引用该对象前必须确认它存在.

 

 1 class MainEntryPoint
 2 {
 3 static void Main()
 4 {
 5 // Instantiate a weak reference to MathTest object
 6 WeakReference mathReference = new WeakReference(new MathTest()); 
 7 MathTest math;
 8 if(mathReference.IsAlive)
 9 {
10 math = mathReference.Target as MathTest;
11 math.Value = 30;
12 Console.WriteLine(
13 "Value field of math variable contains " + math.Value);
14 Console.WriteLine("Square of 30 is " + math.GetSquare());
15 
16 }
17 else
18 {
19 Console.WriteLine("Reference is not available.");
20 }
21 
22 GC.Collect();
23 
24 if(mathReference.IsAlive)
25 {
26 math = mathReference.Target as MathTest;
27 }
28 else
29 {
30 Console.WriteLine("Reference is not available.");
31 }
32 }
33 }
34 
35 // Define a class named MathTest on which we will call a method
36 class MathTest
37 {
38 public int Value;
39 
40 public int GetSquare()
41 {
42 return Value*Value;
43 }
44 
45 public static int GetSquareOf(int x)
46 {
47 return x*x;
48 }
49 
50 public static double GetPi()
51 {
52 return 3.14159;
53 }
54 }
View Code

 

posted @ 2016-10-08 14:33  指间的徘徊  阅读(388)  评论(0编辑  收藏  举报