Using MethodInfo.GetCurrentMethod() in anonymous methods

前端 未结 3 1609
日久生厌
日久生厌 2021-01-18 02:38
public static void Main(string[] args)
{
    Action a = () => Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
    a();
}

This code will r

3条回答
  •  不知归路
    2021-01-18 02:55

    No, there isn't. That's why it is an anonymous method. The name is automatically generated by the compiler and guaranteed to be unique. If you want to get the calling method name you could pass it as argument:

    public static void Main()
    {
        Action a = name => Console.WriteLine(name);
        a(MethodInfo.GetCurrentMethod().Name);
    }
    

    or if you really want a meaningful name you will need to provide it:

    public static void Main()
    {
        Action a = MeaningfullyNamedMethod;
        a();
    }
    
    static void MeaningfullyNamedMethod()
    {
        Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
    }
    

提交回复
热议问题