弱引用和强引用
在应用程序代码内实例化一个类或结构时,只要有代码引用它,就会形成强引用.
如:MyClass myClassVariable = new MyClass();
只要MyClassVariable在作用域内,就存在对对象的强引用,这意味着垃圾回收器不会清理MyClass对象使用的内存,可能随时需要访问MyClass对象,如果MyClass对象很大,并且不经常访问可以创建对象的弱引用.
弱引用:允许创建和使用对象,垃圾回收器运行时就会回收对象释放内存,一般在特定情况下使用弱引用.弱引用使用WeakReference类创建的.
实例:static void Main()
{
WeakReference mathReference = new WeakReference(new MathTest());
MathTest math;
if(mathReference.IsAlive) //用于判断mathReference对象是否被回收,返回True则未被回收
{
math = mathReference.Target as MathTest; //未被回收Target属性返回的是Object类型,用as强制转换为MathTest类型
math.Value = 30;
Console.WriteLine("...............................");
Console.WriteLine("................................");
}
else
{
Console.WriteLine("。。。。。。。。。。。。。。。。。");
}
GC.Collect(); //调用垃圾回收器
if(mathReference,IsAlive) //回收后尝试再次获得MathTest对象,返回false,如果想要使用MathTest对象,就必须实例化一个新的MathTest对象
{
math = mathReference.Target as MathTest;
}
else
{
Console.WriteLine("..............................");
}
}
 
                     
                    
                 
                    
                 
                
            
         
 
         浙公网安备 33010602011771号
浙公网安备 33010602011771号