【问题标题】:Using nameof to get name of current method使用 nameof 获取当前方法的名称
【发布时间】:2016-11-01 02:39:21
【问题描述】:

已经浏览、搜索和希望,但找不到直接的答案。

C# 6.0 中是否有在不指定方法名的情况下使用 nameof 获取当前方法名?

我正在将我的测试结果添加到这样的字典中:

Results.Add(nameof(Process_AddingTwoConsents_ThreeExpectedRowsAreWrittenToStream), result);

如果我不必显式指定方法名称,我宁愿复制+粘贴该行,这是一个无效的示例:

Results.Add(nameof(this.GetExecutingMethod()), result);

如果可能,我不想使用反射。

更新

这不是(如建议的)this question 的副本。我在问是否可以明确地使用 nameof without(!) 反射来获取当前方法名称。

【问题讨论】:

  • 你为什么不使用这个:stackoverflow.com/questions/44153/…?
  • 您可以使用StackTrace 获取此类信息,但这很慢。为了实现自动化,您可以使用代码生成(例如,在编译器之前运行并用其他东西替换某些东西的工具)或 AOP(参见this)。
  • 这样不行吗? System.Reflection.MethodInfo.GetCurrentMethod().Name
  • 他的字面意思是“不使用反射”

标签: c# reflection c#-6.0 nameof


【解决方案1】:

您不能使用nameof 来实现这一点,但是这个解决方法怎么样:

下面没有使用直接反射(就像nameof),也没有明确的方法名称。

Results.Add(GetCaller(), result);

public static string GetCaller([CallerMemberName] string caller = null)
{
    return caller;
}

GetCaller 返回调用它的任何方法的名称。

【讨论】:

  • 这有什么帮助?你需要执行方法的调用者,而不是GetCaller的调用者;除非您提议为 all 可能的可调用方法添加一个可选参数,以使这项工作坦率地说是可怕的。
  • @InBetween OP 声明 "get the current method name" 。这正是他所说的!您只需要一个可以从任何地方调用的GetCaller 方法来获取当前正在执行的方法名称。
  • 我建议使用caller = null,因为这在 imo 中更明显。它也是来自 MS istelf 和 R# 的示例
  • 希望这从一开始就存在... :-(
【解决方案2】:

以 user3185569 的出色回答为基础:

public static string GetMethodName(this object type, [CallerMemberName] string caller = null)
{
    return type.GetType().FullName + "." + caller;
}

导致您可以在任何地方调用 this.GetMethodName() 以返回完全限定的方法名称。

【讨论】:

  • 我如何调用 静态方法 ?无效this
  • @Kiquenet 重载不包含type 参数的GetMethodName(),并像任何其他静态方法一样调用它。例如Util.GetMethodName();
【解决方案3】:

与其他人相同,但有所不同:

    /// <summary>
    /// Returns the caller method name.
    /// </summary>
    /// <param name="type"></param>
    /// <param name="caller"></param>
    /// <param name="fullName">if true returns the fully qualified name of the type, including its namespace but not its assembly.</param>
    /// <returns></returns>
    public static string GetMethodName(this object type, [CallerMemberName] string caller = null, bool fullName = false)
    {
        if (type == null) throw new ArgumentNullException(nameof(type));
        var name = fullName ? type.GetType().FullName : type.GetType().Name;
        return $"{name}.{caller}()";
    }

允许这样称呼它:

Log.Debug($"Enter {this.GetMethodName()}...");

【讨论】:

    【解决方案4】:

    如果你想将当前方法的名称添加到结果列表中,那么你可以使用这个:

    StackTrace sTrace= new StackTrace();
    StackFrame sFrame= sTrace.GetFrame(0);
    MethodBase currentMethodName = sFrame.GetMethod();
    Results.Add(currentMethodName.Name, result);
    

    或者你可以使用,

    Results.Add(new StackTrace().GetFrame(0).GetMethod().Name, result);    
    

    【讨论】:

    • 请注意,这可能不可靠,因为该方法可能是内联的。我也希望它会很慢。
    • 一般来说你不应该在生产代码中使用这些类
    • System.Reflection.MethodInfo.GetCurrentMethod() 会更轻松(而且可能更快)
    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 2011-01-04
    • 2010-10-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    相关资源
    最近更新 更多