垃圾收集和参考C# [英] Garbage collection and references C#

查看:107
本文介绍了垃圾收集和参考C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设计,我不确定垃圾收集是否会正确发生。

我有一些魔法苹果,有些是美味的一些是坏的。

I have a design and I am not sure if garbage collection will occur correctly.
I have some magic apples, and some are yummy some are bad.

我有一本字典: BasketList =字典< basketID,Basket>

(篮子列表)。

I have a dictionary : BasketList = Dictionary <basketID,Basket>
(list of baskets).

每个篮子对象在其中有一个 Apple ,每个 Basket 存储对对象 AppleSeperation 的引用。

AppleSeperation 存储2个字典 YummyApples =< basketID,Apple> BadApples = Dictionary< basketID,Apple> 所以当我被问到我知道苹果是在哪里。

Each Basket object has a single Apple in it and each Basket stores a reference to an objectAppleSeperation.

AppleSeperation stores 2 dictionaries, YummyApples = <basketID,Apple> and BadApples = Dictionary<basketID,Apple>, so when I'm asked where an apple is I know.

一个 Apple > BasketsImIn = Dictionary< ID,Basket> ,指向篮子和商店,以及苹果在篮子里。

An Apple object stores BasketsImIn = Dictionary<ID,Basket>, which points to the Basket and in Shops, and the Apple in Basket.

,如果我从 BasketList 删除一个篮子,并确保我从 BadApples 和/或<$ c $

My question is, if I delete a basket from BasketList and make sure I delete the Apple from BadApples and/or YummyApples, will garbage collection happen properly, or will there be some messy references lying around?

推荐答案

但是,只要你小心删除所有引用,并且你没有任何其他独立的变量保持引用,垃圾收集器将做它的工作。

However, as long as you are careful to remove all references you have set, and you don't have any other free-standing variables holding onto the reference, the garbage collector will do its work.

GC实际上是相当复杂的收集未引用的对象。例如,它可以收集两个引用对象,但在应用程序中没有其他生命引用。

The GC is actually fairly sophisticated at collecting unreferenced objects. For example, it can collect two objects that reference each other, but have no other 'living' references in the application.

这篇关于垃圾收集和参考C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆