C# 使用nameof获取当前方法的名称

C# 使用nameof获取当前方法的名称,c#,reflection,c#-6.0,nameof,C#,Reflection,C# 6.0,Nameof,浏览、搜索、希望,但找不到直接的答案 在C#6.0中,是否仍然可以使用nameof获取当前方法名,而不指定方法名 我将测试结果添加到字典中,如下所示: Results.Add(nameof(Process_AddingTwoConsents_ThreeExpectedRowsAreWrittenToStream), result); Log.Debug($"Enter {this.GetMethodName()}..."); 如果我不必显式指定方法名称,这样我就可以复制并粘贴行,我更愿意这样

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

在C#6.0中,是否仍然可以使用
nameof
获取当前方法名,而不指定方法名

我将测试结果添加到字典中,如下所示:

Results.Add(nameof(Process_AddingTwoConsents_ThreeExpectedRowsAreWrittenToStream), result);
Log.Debug($"Enter {this.GetMethodName()}...");
如果我不必显式指定方法名称,这样我就可以复制并粘贴行,我更愿意这样做,一个不起作用的示例:

Results.Add(nameof(this.GetExecutingMethod()), result);
如果可能,我不想使用反射

更新


这不是(按照建议)的副本。我想问的是,是否可以明确地使用不带(!)反射的
nameof
来获取当前方法名称。

如果要将当前方法的名称添加到结果列表中,则可以使用以下方法:

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);    

您不能使用
nameof
来实现这一点,但该解决方案如何:

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

Results.Add(GetCaller(), result);

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

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

基于user3185569的最佳答案:

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

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

与其他方法相同,但有一些变化:

    /// <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}()";
    }

你为什么不使用这个:?你可以使用
StackTrace
来获取这样的信息,但这很慢。为了实现自动化,您可以使用代码生成(例如,在编译器之前运行并用其他东西替换某些东西的工具)或AOP(请参阅)。这样做不行吗
System.Reflection.MethodInfo.GetCurrentMethod().Name
他字面意思是“不使用反射”,这有什么帮助?您需要执行方法的调用者,而不是
GetCaller
的调用者;除非您建议为所有可能调用的方法添加一个可选参数,以使其正常工作,坦白说,这是非常可怕的。@OP之间声明了
“获取当前方法名”
。这正是他所说的!您只需要一个
GetCaller
方法,您可以从任何地方调用该方法来获取当前的执行方法名称。我建议使用
caller=null
,因为这在我看来更为明显。这也是MS istelf和R#希望从一开始就有这样的例子…:-(请注意,这可能不可靠,因为该方法可能是内联的。我还认为它会非常慢。一般来说,您不应该在生产代码
System中使用这些类。反射。MethodInfo.GetCurrentMethod()
将更容易(而且可能更快)做到这一点)如何调用静态方法?无效
this
@Kiquenet使GetMethodName()重载,该重载不包括
type
参数,并像调用任何其他静态方法一样调用它。例如
Util.GetMethodName();