1

我有一个类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);

调试返回The value of b isAnd the value of the clown in the list is 6.

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

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

帮助任何人?

4

1 回答 1

4

b并且list[0]都是引用内存中相同位置的变量。当您设置时b = null,您正在设置b对 的引用nulllist[0]仍然指向内存中的原始位置并且没有改变。

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

获取 b 指向的任何对象并更新属性 A。

当您访问Avialist[0]时,您是在说

去获取 list[0] 指向的任何内容,然后获取 A 属性。

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

因此,要回答您的问题,您必须将它们都引用的对象设置为“null” b = nulllist[0] = null但是,即使这样,也不会像你想要的那样做。所要做的就是使内存中的对象成为孤立对象,并允许Garbage Collector它在遇到它时对其进行清理。

于 2012-12-28T23:39:50.927 回答