Getting Type T from a StackFrame

后端 未结 1 1778
青春惊慌失措
青春惊慌失措 2021-01-01 06:10

The goal is to create a generic instance based on the type that called my method.

The problem is that when called from a generic, the StackFrame only appears to con

相关标签:
1条回答
  • 2021-01-01 06:40

    The stack frame is not reliable and is for debugging purposes only. You cannot assume that anything useful is there. That's why it is in the "Diagnostics" namespace.

    More generally though, your question demonstrates a fundamental misunderstanding about what the stack frame tells you. You said

    The goal is to create a generic instance based on the type that called my method.

    The stack frame does not actually tell you who called your method. The stack frame tells you where control is going to return to. The stack frame is the reification of continuation. The fact that who called the method and where control will return to are almost always the same thing is the source of your confusion, but I assure you that they need not be the same.

    In particular, the coming "async/await" feature currently in preview release demonstrates the truth of this. Code that resumes from an await has no clue on the stack frame about who called it originally; that information is lost forever. Since the code that is going to run next is logically decoupled from the code that called the method originally, the stack frame does not contain that information.

    We need not get as exotic as that though. For example, suppose a method M contains a call to a method N, and N calls a method O. If the jitter chooses to inline N inside M then the stack frame observed from O will not contain N. The stack frame tells you where control resumes when the current method returns. Control will resume inside M when O returns, not N, so the stack frame does not include any information about N.

    0 讨论(0)
提交回复
热议问题