如何获得此方法的调用类

时间:2011-05-24 09:48:00

标签: c#

有可能吗?

我想获取调用我的方法的类的名称(如foo)(如myMethod)

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

像:

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

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

提前致谢

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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