简体   繁体   中英

Get the name of caller method

Suppose, I am calling GetMethodB() which is passed as an argument to GetmethodA() and GetMethodAA(). How do I get the name of these method who invokes GetMethodB();

ClassName.GetMethodA(GetMethodB());
ClassName.GetMethodAA(GetMethodB());

You cannot do it: at the time GetMethodB is invoked, neither GetMethodA nor GetMethodAA is active.

The invocation sequence looks like this:

  • Your method calls GetMethodB() , and gets its result
  • Your method calls GetMethodA(...) passing it the result of GetMethodB() call
  • Your method calls GetMethodB() again, and gets its result
  • Your method calls GetMethodAA(...) passing it the result of the second GetMethodB() call

In both cases the caller of GetMethodB is your current method, from which the invocation is done.

If GetMethodB needs to know its caller, then you should identify the caller to the method explicitly - for example, by passing an enum or a string parameter.

These two methods are called with the result of getmethodB, so the caller of getmethodB is the same one as the caller of getmethodA and/or getmethodAA. You cannot find out to which method the result of another method is passed.

  • So first getMethodB is called,
  • the result is captured
  • and passed to the other methods.

Callstacks or any other tricks won't help here.

Use the StackFrame

var sf = new StackTrace().GetFrame(1);
var callingMethodName = sf.GetMethod().Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM