Reputation: 9393
Suppose I have an Object
o, and an Action
a that was constructed from a lambda. Is there any way I can use (e.g.) reflection or the GC to determine whether a captures o?
Upvotes: 1
Views: 53
Reputation: 171206
I understand you are OK with an approximate solution. In that case you can indeed use Reflection to traverse the object graph. All object references except those on the stack are visible through reflection. You need to look at all fields and all array elements.
Writing this is not that hard but it's quite unreliable and slow. If you are unlucky your traversal will find huge object graphs and spend a lot of time collecting them.
Maybe you can simplify the problem to say that only direct references from a.Target
to o
count. That would be easier. Simply look at all field values of a.Target
.
There is no built-in API to do any of this, and thank god for that. This is the ultimate layering violation because no implementation detail remains hidden.
Upvotes: 1