简体   繁体   中英

Find out what class invoked a method

Is there any way, in C#, for a class or method to know who (ie what class/ method) invoked it?

For example, I might have

class a{
   public void test(){
         b temp = new b();
         string output = temp.run();
   }
}

class b{
   public string run(){
        **CODE HERE**
   }
}

Output: "Invoked by the 'test' method of class 'a'."

StackFrame

var frame = new StackFrame(1);

Console.WriteLine("Called by method '{0}' of class '{1}'",
    frame.GetMethod(),
    frame.GetMethod().DeclaringType.Name);

You can look at the stack trace to determine who called it.

http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx

您可以创建并检查System.Diagnostics.StackTrace

The following expression will give you the calling method.

new StackTrace() . GetFrame(1) . GetMethod()

StackFrame will do it, as Jimmy suggested. Beware when using StackFrame, however. Instantiating it is fairly costly, and depending on exactly where you instantiate it, you may need to specify MethodImplOptions.NoInlining. If you wish to wrap up the stack walk to find the callee's caller in a uttily function, you'll need to do this:

[MethodImpl(MethodImplOptions.NoInlining)]
public static MethodBase GetThisCaller()
{
    StackFrame frame = StackFrame(2); // Get caller of the method you want
                                      // the caller for, not the immediate caller
    MethodBase method = frame.GetMethod();
    return method;
}

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