【问题标题】:C# Reflection: Obtain a list of references to a specific instance?C# 反射:获取对特定实例的引用列表?
【发布时间】: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


【解决方案1】:

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

以下危险读物;非常低效,但确实有效

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

Object.ReferenceEquals(this, obj2);

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

我现在没有更多时间,但如果需要,我可以插话并提供一些 sn-ps。

【讨论】:

    【解决方案2】:

    我认为就内置 .NET 机制而言这是不可能的。见How do I iterate through instances of a class in 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;
    

    【讨论】:

      猜你喜欢
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多