I mean I want to get the references of
object in a.do_A() (can be easily
attained by this), the reference of
object b that called a.do_A(), and the
reference of object c that called
b.do_B().
I think this should be possible,
because I can get the call hierarchy
with call stack, so I'm sure I should
be able to get some more information
about the objects who called the
methods.
In general, what you ask for is not possible in .NET - even in theory. Perhaps unintuitively, there's no guarantee that an object is still alive even when an instance-method on that object is in the midst of execution. Essentially, the CLR is smart enough to recognize when the hidden this
reference passed to an instance-method will no longer be dereferenced. The referenced object can then become eligible for collection when this happens (assuming it is not reachable through other roots, of course).
As a corollary, it's also perfectly possible for a "calling object" to be dead while the method it has called is still executing. In your specific example, it's perfectly possible that b
and c
(really the objects referred to by those variables) don't exist anymore while A.do_A()
is executing.
What this means of course is that the information you seek may no longer be available in any form in the process, and no "magic" API should be able to reliably produce it.
I recommend reading Raymond Chen's article: When does an object become available for garbage collection? to understand this issue better:
An object can become eligible for
collection during execution of a
method on that very object.
If you feel this doesn't relate to your question, consider the second-last paragraph in that article:
Another customer asked, "Is there a
way to get a reference to the instance
being called for each frame in the
stack? (Static methods excepted, of
course.)" A different customer asked
roughly the same question, but in a
different context: "I want my method
to walk up the stack, and if its
caller is OtherClass.Foo, I want to
get the this object for OtherClass.Foo
so I can query additional properties
from it." You now know enough to
answer these questions yourself.