c# - 清空对对象的所有引用

标签 c#

<分区>

我有一个 Simple 类,它包含一个整数 number。 使用此代码:

Simple b = new Simple();
List<Simple> list = new List<Simple>();
list.Add(b);
b.number = 6;
b = null;
Debug.WriteLine("The value of b is " + b);
Debug.WriteLine("And the value of the clown in the list is " + list[0].number);

Debugs 返回b 的值为列表中 clown 的值为6

我可以假设通过将 b 添加到 list,然后存储对 b 的引用。然后,通过清空 blist 仍然包含对 b 对象的引用,因此可以打印出 number 的值

但是,如果我可以更改 b 的成员并通过存储在列表中的引用反射(reflect)它,那么为什么 b = null 不反射(reflect)list[0] 的值?我只能假设这与值(value)和引用有关。

帮助任何人?

最佳答案

blist[0] 都是引用内存中相同位置的变量。当您设置 b = null 时,您将 b 的引用设置为 nulllist[0] 仍然指向内存中原来的位置,没有改变。

当您更改 b 的属性时(例如 b.A),您实际上是在说

Get whatever object b is pointing to and update property A.

当您通过 list[0] 访问 A 时,您说的是

Go get whatever list[0] is pointing to and get me the A property.

编辑:作为另一个例子,如果 b = someObjectlist[0] = someObject,设置 b = someOtherObject 不会改变 list[0]... list[0] 仍然指向 someObject

因此,要回答您的问题,您必须将 b = nulllist[0] = null 设置为“null”它们都是的对象引用。尽管如此,即使那样,也不会像你想要的那样做。所有要做的就是在内存中孤立该对象,并允许垃圾收集器在它到达时清理它。

关于c# - 清空对对象的所有引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14077124/

相关文章:

c# - 如何在C#项目中实现和做OCR?

c# - 从类返回多个值到方法

c# - 从现有实例创建 IList<T> 的新实例并修改它

c# - 计算缩放级别以使图像适合面板

c# - 在 Mono 下隔离非托管崩溃

c# - 在 f# 中实现接口(interface)

java - 绑定(bind)java库Xamarin.Android

C#获取数据包

c# - 如何在 MVC Core 中使用缓存管理器?

c# - 我怎样才能找出一个类创建了多少个对象