zoukankan      html  css  js  c++  java
  • C# 弱引用WeakReferance

      在应用程序代码内实例化一个类或结构时,只要有代码引用它,就会形成强引用。例如,如果有一个类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;
                }
                else
                {
                    Console.WriteLine("Referance is not available");
                }
                Console.ReadKey();
            }
        }

    //测试用的类,此类并不是最好的设计,只是作为例子运用;如得到PI的值,一般在类中声明为(const)常量。
        class MathTest
        {
            public int value;
            public int GetSquare()//实例方法得到value的平方。
            {
                return value * value;
            }
            public static int GetSquareOf(int x)//静态方法得到x的平方。
            {
                return x * x;
            }
            public static double GetPI()//静态方法得到PI的值
            {
                return 3.1415926;
            }
        }

    输出为:30

            900

  • 相关阅读:
    Fiddler抓包工具-拦截,断点
    python-zx笔记11-测试压力管理
    python-zx笔记10-断言
    python-zx笔记9-单元测试
    [Trouble shooting] Alt-A shortcut taken by another app and conflict with Emacs' M-a
    Dwango Programming Contest 6th Task C. Cookie Distribution
    局部有限偏序集上的 Möbius 函数
    一个求和
    一个组合问题
    ABC #150 E. Change a Little Bit
  • 原文地址:https://www.cnblogs.com/zhangyuanbo12358/p/3714777.html
Copyright © 2011-2022 走看看