【发布时间】:2014-07-14 17:45:35
【问题描述】:
public class AAA {
public BBB fieldInstance;
}
public class BBB {
public void Method() {
//I would like to obtain a reference to the object(s) that
//are pointing at this instance of BBB.
}
}
假设我有一个如上所示的简单类结构,有没有办法获取所有对象的列表,这些对象包含对 BBB 实例的引用,该实例调用了 Method()?
//Example
AAA aaa = new AAA();
aaa.fieldInstance = new BBB();
aaa.fieldInstance.Method();
//Method should obtain a reference to aaa.
显然,这是一个玩具示例,因为 Method() 可以轻松地将 aaa 的引用作为参数。我仍然很想知道这是否可能。我会假设垃圾收集器拥有所有这些信息,但我不知道如何访问它。
【问题讨论】:
-
这完全不可能。
-
GC 不跟踪引用。它每次都构建可访问性树。根是静态字段和当前执行方法的局部变量。一切可从根源获得的东西都将在收集中幸存下来。永远不会检查其他所有内容。
-
不完全是重复的,不。虽然有一个答案确实回答了另一个。这是关于对实例的引用。另一个是关于类型的引用。
标签: c# reflection reference-counting