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

本文关键字:方法 nameof 获取 使用 | 更新日期: 2023-09-27 17:52:59

浏览,搜索,希望,但无法找到一个直接的答案。

是否在c# 6.0中使用nameof而不指定方法名称来获取当前方法名称?

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

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

我希望我不需要显式地指定方法名,这样我就可以复制+粘贴这行,一个不工作的例子:

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

如果可能的话,我不想使用Reflection

这不是(如建议的)这个问题的重复。我问是否可以显式地使用没有(!)反射的nameof来获得当前方法名称。

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

你不能使用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}()";
    }

允许这样调用:

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

如果你想将当前方法的名称添加到Results List中,那么你可以使用:

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