Find out which class is invoked by the method

Is there a way in C # for a class or method to find out who (i.e. which class / method) called it?

For example, I may have

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

Conclusion: "Called by the" test "method of class" a ".

+4
source share
5 answers

Stackframe

 var frame = new StackFrame(1); Console.WriteLine("Called by method '{0}' of class '{1}'", frame.GetMethod(), frame.GetMethod().DeclaringType.Name); 
+13
source

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

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

+2
source

You can create and research a System.Diagnostics.StackTrace check

+1
source

The following expression will give you a call method.

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

0
source

StackFrame will do this as Jimmy suggested. However, beware of using a StackFrame. Creating an instance is quite expensive and depending on where exactly you create it, you may need to specify MethodImplOptions.NoInlining. If you want to complete the stack to find the caller in full function, you 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; } 
0
source

Source: https://habr.com/ru/post/1286112/


All Articles