【问题标题】:Get the name of the currently executing method in dotnet core获取 dotnet core 中当前执行方法的名称
【发布时间】:2016-12-13 01:28:28
【问题描述】:

我想获取 dotnet 核心应用程序中当前正在执行的方法的名称。

有很多例子说明如何使用常规 c# 来做到这一点,例如

但是,这两种方法的 api 似乎还没有在核心中出现(请参阅https://github.com/dotnet/corefx/issues/1420

还有其他方法可以在 .net core 中获取执行方法名称吗?

【问题讨论】:

  • 为什么不直接使用nameof(YourCurrentMethod)
  • 另外,更相关的 GitHub 问题是 github.com/dotnet/corefx/issues/12496
  • nameof(YourCurrentMethod) 并不比仅使用字符串好多少,感谢问题链接,看来该方法也将在未来的版本中到期。也许答案是不可能的atm
  • 不,它比使用字符串要好得多。如果您重命名函数,如果您使用重命名工具,nameof(YourCurrentMethod) 也会更新(如果不使用,则会出现编译器错误提醒您修复它)

标签: c# .net-core


【解决方案1】:

CallerMemberNameAttribute 允许您获取方法调用者的方法或属性名称。

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    System.Diagnostics.Trace.WriteLine("message: " + message);
    System.Diagnostics.Trace.WriteLine("member name: " + memberName);
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
    System.Diagnostics.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

【讨论】:

    【解决方案2】:

    最简单的方法是使用:

    System.Reflection.MethodBase.GetCurrentMethod().Name

    【讨论】:

    • 曾经可以工作 - 但在 asp.net core 中不起作用:(
    • 它没有,但它确实: System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name 。我应该注意它不会返回确切的方法名称,但它非常接近并且满足我的需要,足够独特。例如,我有一个名为 GetMembersAsync() 的方法,它将返回一个值“D__18”。
    【解决方案3】:

    在 .Net Core 3.1 中,要获取当前方法名称,请使用:

    MethodBase.GetCurrentMethod().Name
    

    【讨论】:

    • 在异步方法中不起作用,返回“MoveNext”。
    猜你喜欢
    • 2010-10-01
    • 2023-03-10
    • 2016-03-13
    • 2011-01-04
    • 2010-09-19
    • 2013-06-18
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多