当登录c#时,我如何才能知道调用当前方法的方法的名称?我知道所有关于System.Reflection.MethodBase.GetCurrentMethod(),但我想在堆栈跟踪中走一步。我考虑过解析堆栈跟踪,但我希望找到一种更清晰、更显式的方式,比如Assembly.GetCallingAssembly(),但用于方法。
当前回答
显然这是一个迟来的答案,但如果你能使用。net 4.5或更新版本,我有一个更好的选择:
internal static void WriteInformation<T>(string text, [CallerMemberName]string method = "")
{
Console.WriteLine(DateTime.Now.ToString() + " => " + typeof(T).FullName + "." + method + ": " + text);
}
这将打印当前的日期和时间,后面跟着“Namespace.ClassName”。并以“:text”结尾。 样例输出:
6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized
示例使用:
Logger.WriteInformation<MainWindow>("MainWindow initialized");
其他回答
通常,您可以使用System.Diagnostics. stacktrace类来获取System.Diagnostics。然后使用GetMethod()方法获取System.Reflection.MethodBase对象。然而,这种方法有一些注意事项:
它表示运行时堆栈——优化可以内联一个方法,并且您不会在堆栈跟踪中看到该方法。 它不会显示任何本机帧,所以即使有机会您的方法被本机方法调用,这也将不起作用,而且实际上目前没有可用的方法来做到这一点。
(注:我只是在扩展Firas Assad提供的答案。)
我们可以对阿萨德先生的代码(目前公认的答案)稍加改进,只实例化我们实际需要的帧而不是整个堆栈:
new StackFrame(1).GetMethod().Name;
这可能会执行得更好一些,尽管在所有的可能性中,它仍然需要使用整个堆栈来创建单个帧。此外,它仍然有Alex Lyman指出的同样的警告(优化器/本机代码可能会破坏结果)。最后,你可能想要检查以确保新的StackFrame(1)或. getframe(1)不返回null,因为这种可能性看起来不太可能。
请看这个相关问题: 您可以使用反射来查找当前正在执行的方法的名称吗?
显然这是一个迟来的答案,但如果你能使用。net 4.5或更新版本,我有一个更好的选择:
internal static void WriteInformation<T>(string text, [CallerMemberName]string method = "")
{
Console.WriteLine(DateTime.Now.ToString() + " => " + typeof(T).FullName + "." + method + ": " + text);
}
这将打印当前的日期和时间,后面跟着“Namespace.ClassName”。并以“:text”结尾。 样例输出:
6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized
示例使用:
Logger.WriteInformation<MainWindow>("MainWindow initialized");
从。net 4.5开始,你可以使用调用者信息属性:
CallerFilePath - The source file that called the function; CallerLineNumber - Line of code that called the function; CallerMemberName - Member that called the function. public void WriteLine( [CallerFilePath] string callerFilePath = "", [CallerLineNumber] long callerLineNumber = 0, [CallerMemberName] string callerMember= "") { Debug.WriteLine( "Caller File Path: {0}, Caller Line Number: {1}, Caller Member: {2}", callerFilePath, callerLineNumber, callerMember); }
这一设施也出现在“。NET Core"和"。净标准”。
参考文献
微软-呼叫者信息(c#) CallerFilePathAttribute类 CallerLineNumberAttribute类 CallerMemberNameAttribute类
private static MethodBase GetCallingMethod()
{
return new StackFrame(2, false).GetMethod();
}
private static Type GetCallingType()
{
return new StackFrame(2, false).GetMethod().DeclaringType;
}
这里有一个很棒的课程:http://www.csharp411.com/c-get-calling-method/
推荐文章
- 最好的方法在asp.net强制https为整个网站?
- 将字符串转换为System.IO.Stream
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 有nginx access_log和error_log日志的STDOUT和STDERR的主进程
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法