2011-05-24 55 views
3

是否有可能?如何获取此方法的调用者类

我想类(如富)的名字被调用我的方法(如myMethod的)

(和方法在另一个类(像我))

,如:

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

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

在此先感谢

+1

我不禁纳闷,为什么* *您想知道... – forsvarir 2011-05-24 09:52:18

回答

9

您可以使用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); 
+0

是否有交付堆属性逐帧跟踪,还是我们必须解析字符串属性? – 2011-05-24 09:53:00

+0

@Jen:你在哪里可以看到我提供的代码中的任何字符串属性? – 2011-05-24 09:53:32

+0

提及内联+1。除非使用属性来显式禁用它,否则这会很危险,甚至在Debug和Release版本中可能会有不同的工作方式。 – takrl 2011-05-24 09:58:12

0

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