1

我有一个功能

public void AddPerson(string name)
{
    Trace.WriteLine(MethodBase.GetCurrentMethod());
}

预期的输出是

void AddPerson(string name)

但我希望输出的方法名中没有参数。

void AddPerson()
4

2 回答 2

3

要可靠地做到这一点将成为一个问题,您将不得不构建它,即返回类型、名称、泛型类型、访问修饰符等。

例如:

static void Main(string[] args)
{
   var methodBase =  MethodBase.GetCurrentMethod() as MethodInfo;
     
   Console.WriteLine($"{methodBase.ReturnType.Name} {methodBase.Name}()");
}

输出

Void Main()

陷阱,你在追逐一个移动的目标:

public static (string, string) Blah(int index)
{
   var methodBase =  MethodBase.GetCurrentMethod() as MethodInfo;
   Console.WriteLine(MethodBase.GetCurrentMethod());
   Console.WriteLine($"{methodBase.ReturnType.Name} {methodBase.Name}()");
   return ("sdf","dfg");
}

输出

System.ValueTuple`2[System.String,System.String] Blah(Int32)
ValueTuple`2 Blah()

另一个选项只是用这样的方式将参数正则表达式:(?<=\().*(?<!\)).

于 2018-10-25T00:52:25.843 回答
1

GetCurrentMethod方法返回一个MethodBase对象,而不是字符串。因此,如果您想要与返回的字符串不同的字符串.ToString(),您可以将属性中的字符串拼凑在一起,MethodBase或者只返回Name属性,例如:

Trace.WriteLine(MethodBase.GetCurrentMethod().Name);
于 2018-10-25T00:50:39.757 回答