簡體   English   中英

使用 nameof 獲取當前方法的名稱

[英]Using nameof to get name of current method

瀏覽、搜索並希望但找不到直接的答案。

無論如何,在 C# 6.0 中是否可以使用nameof獲取當前方法名稱nameof指定方法名稱?

我將我的測試結果添加到這樣的字典中:

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

如果我不必顯式指定方法名稱,我會更喜歡這樣我可以復制+粘貼該行,一個非工作示例:

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

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

更新

這不是(如建議的) 此問題的副本。 我在問是否可以明確地使用nameof without(!) 反射來獲取當前方法名稱。

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

如果要將當前方法的名稱添加到結果列表中,則可以使用以下命令:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM