Using System.Reflection to Get a Method's Full Name

后端 未结 8 1420
执念已碎
执念已碎 2020-12-13 06:00

I have a class that look like the following:

public class MyClass
{

...

    protected void MyMethod()
    {
    ...
    string myName = System.Reflection.M         


        
8条回答
  •  北海茫月
    2020-12-13 06:25

    You'll have issues when running inside async methods. Here's how to fix that:

    If you need to fully qualify the class name, you'll have to use DeclaringType.FullName instead of DeclaringType.Name

    This code won't work nicely for anonymous or lambda methods.

    using System.Runtime.CompilerServices;
    
    static string GetMethodContextName() {
        var name = new StackTrace().GetFrame(1).GetMethod().GetMethodContextName();
        return name;
    }
    
    static string GetMethodContextName(this MethodBase method) {
        if (method.DeclaringType.GetInterfaces().Any(i => i == typeof(IAsyncStateMachine))) {
            var generatedType = method.DeclaringType;
            var originalType = generatedType.DeclaringType;
            var foundMethod = originalType.GetMethods(
                  BindingFlags.Instance | BindingFlags.Static 
                | BindingFlags.Public | BindingFlags.NonPublic 
                | BindingFlags.DeclaredOnly)
                .Single(m => m.GetCustomAttribute()?.StateMachineType == generatedType);
            return foundMethod.DeclaringType.Name + "." + foundMethod.Name;
        } else {
            return method.DeclaringType.Name + "." + method.Name;
        }
    }
    

    Here's an example usage:

    class Program { 
        static void Main(string[] args) {
            // outputs Program.Main
            Console.WriteLine(GetMethodContextName());
        }
    }
    

提交回复
热议问题