c#反射:获取对特定实例的引用列表

本文关键字:实例 引用 列表 反射 获取 | 更新日期: 2023-09-27 18:04:58

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作为参数。我还是很想知道这是否可能。我假设垃圾收集器拥有所有这些信息,但是我不知道如何访问它。

c#反射:获取对特定实例的引用列表

没有开始元素是完全不可能的。

下面危险读数;效率非常低,但是完成了工作

另一方面,如果你有一个开始元素,你可以使用反射来遍历所有引用类型的属性和字段,看看它们是否引用了这个,例如:

Object.ReferenceEquals(this, obj2);

然后递归地对值和引用类型的属性和字段做同样的事情。

我现在没有更多的时间,但如果需要的话,我可以回来提供一些片段。

我不认为这在内建的。net机制方面是可能的。参见如何在c#中迭代一个类的实例?

你当然可以做一些手工跟踪(但这将是你的责任)。简单的例子:

public static class Watch<T> where T : class {
  static IList<object> s_References = new List<object>();
  public static T Observe<T>(object referrer, T instance) {
    if (!s_References.Contains(referrer)) {
      s_References.Add(referrer);
    }
    return instance;
  }
  public static IList<object> References {
    get { return new ReadOnlyCollection<object>(s_References); }
  }
}
AAA aaa = new AAA();
aaa.fieldInstance = Watch<BBB>.Observe(aaa, new BBB());
AAA ccc = new AAA();
ccc.fieldInstance = Watch<BBB>.Observe(ccc, new BBB());
var foo = Watch<BBB>.References;