如何获取该方法的invoker类

本文关键字:方法 invoker 何获取 获取 | 更新日期: 2023-09-27 17:57:36

有可能吗?

我想得到调用我的方法(比如myMethod(的类(比如foo(的名称

(该方法属于另一类(如i((

类似:

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

提前感谢

如何获取该方法的invoker类

您可以使用StackTrace来计算调用者,但前提是没有内联。堆栈跟踪并不总是100%准确。类似于:

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

我发现休耕: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