How do I get the executing object for a stackframe?

后端 未结 3 1208
轻奢々
轻奢々 2021-01-01 22:55

When using reflection it is possible to obtain the call stack (apart from that it can be a crude approximation due to JIT optimizations) using System.Diagnostics.StackTrace

3条回答
  •  暖寄归人
    2021-01-01 23:45

    I'm pretty sure that this is not possible. Here's why:

    1. This could break type safety, since anyone can lookup a frame, get the object regardless of which AppDomain\Thread they are executing on or permission they have.

    2. The 'this' (C#) identifier is really just an argument to the instance method (the first), so in reality there is no difference between static methods and instance methods, the compiler does its magic to pass the right this to an instance method, which of course means that you will need to have access to all method arguments to get the this object. (which StackFrame does not support)

    It might be possible by using unsafe code to get the pointer of the first argument to an instance method and then casting it to the right type, but I have no knowledge of how to do that, just an idea.

    BTW you can imagine instance methods after being compiled to be like C# 3.0 extension methods, they get the this pointer as their first argument.

提交回复
热议问题