46

Have browsed, searched and hoped but cannot find a straight answer.

Is there anyway in C# 6.0 to get the current method name using nameof withouth specifying the method name?

I am adding my test results to a dictionary like this:

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

I would prefer if I would not have to specify the method name explicitly so I can copy+paste the line, a non-working example:

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

If possible I do not want to use Reflection.

UPDATE

This is not (as suggested) a duplicate of this question. I am asking if is explicitly possible to make use of nameof without(!) reflection to get the current method name.

4

4 回答 4

96

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

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

Results.Add(GetCaller(), result);

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

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

于 2016-06-29T12:00:55.290 回答
12

基于 user3185569 的出色答案:

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

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

于 2018-05-02T02:33:11.387 回答
1

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

    /// <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()}...");
于 2019-11-18T17:06:09.407 回答
-1

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

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);    
于 2016-06-29T11:59:52.560 回答