How to get the invoker class of this method

Is it possible?

I want to get a class name (e.g. foo) that calls my method (e.g. myMethod)

(and the method is in another class (e.g. i))

as:

class foo
{
    i mc=new i;
    mc.mymethod();

}
class i
{
    myMethod()
    {........
       Console.WriteLine(InvokerClassName);// it should writes foo
    }
}

early

+3
source share
2 answers

You can use StackTraceto work out the caller, but on the condition that there is no insertion. Stack traces are not always 100% accurate. Sort of:

StackTrace trace = new StackTrace();
StackFrame frame = trace.GetFrame(1); // 0 will be the inner-most method
MethodBase method = frame.GetMethod();
Console.WriteLine(method.DeclaringType);
+9
source

I found the following: http://msdn.microsoft.com/en-us/library/hh534540.aspx

// using System.Runtime.CompilerServices 
// using System.Diagnostics; 

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
{
    Trace.WriteLine("message: " + message);
    Trace.WriteLine("member name: " + memberName);
    Trace.WriteLine("source file path: " + sourceFilePath);
    Trace.WriteLine("source line number: " + sourceLineNumber);
}

// Sample Output: 
//  message: Something happened. 
//  member name: DoProcessing 
//  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs 
//  source line number: 31
0
source

All Articles