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

  • 相关阅读:
    Spark学习之路 九、SparkCore的调优之数据倾斜调优
    Spark学习之路 八、SparkCore的调优之开发调优
    Spark Core、Spark Sql、Spark Streaming 联系与区别
    Spark学习之路 七、Spark 运行流程
    Spark学习之路 六、Spark Transformation和Action
    Spark学习之路 五、Spark伪分布式安装
    一起来学习Shell脚本
    简单整理React的Context API
    阅读别人项目源码时的随手记(乱七八糟待归类整理)
    React.Component 与 React.PureComponent(React之性能优化)
  • 原文地址:https://www.cnblogs.com/zhangyuanbo12358/p/3714777.html
Copyright © 2011-2022 走看看