在应用程序代码内实例化一个类或结构时,只要有代码引用它,就会形成强引用.这意味着垃圾回收器不会清理这样的对象使用的内存.但是如果当这个对象很大,并且不经常访问时,此时可以创建对象的弱引用,弱引用允许创建和使用对象,但是垃圾回收器 运行时,就会回收对象并释放内存.

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

using System;

namespace ConsoleAppDemo
{
    class MathTest
    {
        public int Value { get; set; }

        public int GetSquare()
        {
            return this.Value * this.Value;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            WeakReference mathReference = new WeakReference(new MathTest());
            MathTest math;
            if (mathReference.IsAlive)
            {
                math = mathReference.Target as MathTest;
                math.Value = 30;
                Console.WriteLine("Value field of math variable contains " + math.Value);
                Console.WriteLine("Square of 30 is " + math.GetSquare());
            }
            else
            {
                Console.WriteLine("Reference is not avaliable.");
            }
            GC.Collect();
            if (mathReference.IsAlive)
            {
                math = mathReference.Target as MathTest;
                Console.WriteLine("Value field of math variable contains " + math.Value);
            }
            else
            {
                Console.WriteLine("Reference is not available.");
            }
        }
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-05-15
  • 2021-06-08
  • 2021-11-20
  • 2021-11-08
  • 2022-12-23
猜你喜欢
  • 2021-09-09
  • 2021-04-30
  • 2021-12-16
  • 2021-11-13
  • 2021-11-11
  • 2021-10-07
相关资源
相似解决方案