花露水小龙虾 發表於 2025-12-19 10:59:00

C#中弱引用使用小结

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>核心概念​​</li><li>使用:</li><ul class="second_class_ul"><li>1.基础使用:</li><li>2.泛型使用:</li></ul><li>适用场景:</li><ul class="second_class_ul"></ul><li>总结:</li><ul class="second_class_ul"></ul></ul></div><p><strong>弱引用(Weak Reference)</strong>是一种特殊的引用类型,它允许你引用一个对象,但不会阻止该对象被垃圾回收器(GC)回收。弱引用通常用于需要缓存或跟踪对象,但又不希望因保留引用而导致内存泄漏的场景。弱引用对小对象没有意义,因为弱引用有自己的开销,这个开销可能比小对象更大。</p>
<p class="maodian"></p><h2>核心概念​​</h2>
<p>​​<strong>与强引用的区别​​</strong>:<br /><strong>​​强引用​​</strong>:普通对象引用(如 var obj = new MyClass())会阻止 GC 回收对象。<br /><strong>​​弱引用</strong>​​:<span><strong>不会阻止 GC 回收对象</strong></span>。当对象只有弱引用时,GC 可以随时回收它。<br /><strong>​​用途​​</strong>:<br />缓存大型数据(如图片、文件等),当内存不足时自动释放。<br />避免因长期持有对象引用而导致内存泄漏。<br />监听事件或观察对象生命周期,但不干预其回收。</p>
<p class="maodian"></p><h2>使用:</h2>
<p class="maodian"></p><h3>1.基础使用:</h3>
<p>代码:</p>
<div class="jb51code"><pre class="brush:csharp;">public class WeakReferenceTest : MonoBehaviour
{
    WeakReference weakRef;
    // Start is called before the first frame update
    void Start()
    {
      // 创建一个对象
      var myObject = new TestWeakReferenceObj();

      // 创建弱引用
      weakRef = new WeakReference(myObject);

      // 解除强引用,只保留弱引用
      myObject = null;

      // 通过弱引用访问对象
      if (weakRef.IsAlive)
      {
            var obj = weakRef.Target as TestWeakReferenceObj;
            obj.DoSomething();
      }
      else
      {
            Debug.Log("对象已被回收");
      }
    }

    // Update is called once per frame
    void Update()
    {
      // 通过弱引用访问对象
      if (weakRef.IsAlive)
      {
            var obj = weakRef.Target as TestWeakReferenceObj;
            obj.DoSomething();
      }
      else
      {
            Debug.Log("对象已被回收");
      }
    }
}

class TestWeakReferenceObj {
    public void DoSomething()
    {
      Debug.Log("对象没有被回收");
    }
}</pre></div>
<p>结果:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202512/2025121910581661.png" /></p>
<p class="maodian"></p><h3>2.泛型使用:</h3>
<p>代码:</p>
<div class="jb51code"><pre class="brush:csharp;">public class WeakReferenceTest : MonoBehaviour
{
    WeakReference&lt;TestWeakReferenceObj&gt; weakRefGeneric;
    // Start is called before the first frame update
    void Start()
    {
      weakRefGeneric = new WeakReference&lt;TestWeakReferenceObj&gt;(new TestWeakReferenceObj());

      if (weakRefGeneric.TryGetTarget(out TestWeakReferenceObj obj))
      {
            obj.DoSomething();
      }
      else
      {
            Debug.Log("对象已被回收");
      }
    }

    // Update is called once per frame
    void Update()
    {
      if (weakRefGeneric.TryGetTarget(out TestWeakReferenceObj obj))
      {
            obj.DoSomething();
      }
      else
      {
            Debug.Log("对象已被回收");
      }
    }
}

class TestWeakReferenceObj {
    public void DoSomething()
    {
      Debug.Log("对象没有被回收");
    }
}</pre></div>
<p>结果:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202512/2025121910581639.png" /></p>
<p class="maodian"></p><h2>适用场景:</h2>
<p>​<strong>​缓存​</strong>​:缓存大型对象,但允许 GC 在需要时回收它们。<br /><strong>事件监听</strong>​​:避免事件订阅导致的内存泄漏。<br />​​<strong>对象生命周期跟踪</strong>​​:观察对象是否存活,但不阻止其回收。</p>
<p><strong>注</strong>:<br /><strong>性能</strong>​​:频繁检查弱引用是否存在可能影响性能。<br /><strong>​​不确定性</strong>​​:对象可能在任何时候被回收,需始终检查 IsAlive 或 TryGetTarget。<br /><strong>​​短期弱引用</strong>(Short Weak Reference)​​:默认行为,GC 回收后弱引用自动失效。<br /><strong>​​长期弱引用</strong>(Long Weak Reference)​​:通过 WeakReference 构造函数指定 trackResurrection 为 true,可跟踪对象在终结后的状态(但极少使用)。</p>
<p class="maodian"></p><h2>总结:</h2>
<p>弱引用是 C# 中管理内存的一种高级机制,适用于<span><strong>需要灵活控制对象生命周期</strong></span>的场景。正确使用它<span><strong>可以优化内存使用</strong></span>,但<span><strong>需谨慎处理对象可能随时被回收</strong></span>的情况。</p>
<p>到此这篇关于C#中弱引用使用小结的文章就介绍到这了,更多相关C# 弱引用内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>C#值类型和引用类型的深入理解</li><li>C#中的值传递和引用传递详细解析</li><li>C#中值类型和引用类型的区别深度分析</li><li>c# 引用类型与值类型的区别详解</li><li>C# List引用类型克隆的3种方法</li><li>C#: 引用变量与数值变量的区别</li><li>c# 引用类型和值类型</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: C#中弱引用使用小结