如何获得此方法的调用类

可能吗?

我想得到类的名称(如foo),它正在调用我的方法(如myMethod)

(并且该方法在另一个类中(如i))

喜欢:

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

提前致谢

您可以使用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