微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何获得此方法的调用程序类

如何解决如何获得此方法的调用程序类

| 可能吗? 我想获取调用我的方法(如myMethod)的类(如foo)的名称 (并且该方法在另一个类中(例如i)) 喜欢:
class foo
{
    i mc=new i;
    mc.mymethod();

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

解决方法

您可以使用ѭ1来计算出呼叫者-但这假设没有内联。堆栈跟踪不一定总是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
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。