弱应用

弱应用:
在应用程序代码内实例化一个类或结构时,只要有代码引用它,就会形成强引用。例如,如果 有一个类 MyClass(),并创建了一个变量 myClassVariable 来引用该类的对象,那么只要 myClassVariable 在作用域内,就存在对 MyClass 对象的强引用,如下所示:
MyClass myClassVariable = new MyClass();
这意味着垃圾回收器不会清理 MyClass 对象使用的内存。一般而言这是好事,因为可能需要访 问MyClass 对象,但是如果 MyClass 对象很大,并且不经常访问呢?此时可以创建对象的弱引用。 弱引用允许创建和使用对象,但是垃圾回收器运行时,就会回收对象 并释放内存。
由于存在潜在的 bug 和性能问题,一般不会这么做,但是在特定的情况下使用弱引用 是很合理的。

class ww
    {
        public int   aa;
        public string  GetSquare()
        {

            Console.WriteLine("good");
            return "morning";
        }
    
    }
    class Program
    {
       
        static void Main(string[] args)
        {

            WeakReference wr = new WeakReference(new ww());
            ww w;
            w = wr.Target as ww;

            if (w != null)
            {
                w.aa = 30; Console.WriteLine("Value field of math variable contains " + w.aa);
 Console.WriteLine("Square of 30 is " + w.GetSquare());
} else { Console.WriteLine("Reference is not available."); }  
GC.Collect();
if (wr.IsAlive)
{ w = wr.Target as ww; Console.WriteLine("!!"); } else { Console.WriteLine("Reference is not available."); }
            Console.WriteLine(  );
            Console.ReadKey();
           
           
            
           
        }

原文地址:https://www.cnblogs.com/zhubenxi/p/5168343.html