Get the name of a method using an expression

后端 未结 6 1158
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 12:03

I know there are a few answers on the site on this and i apologize if this is in any way duplicate, but all of the ones I found does not do what I am trying to do.

I

6条回答
  •  抹茶落季
    2020-11-28 12:29

    If you are ok with using the nameof() operator you can use the following approach.

    One of the benefits is not having to unwrap an expression tree or supply default values or worry about having a non-null instance of the type with the method.

    // As extension method
    public static string GetMethodName(this T instance, Func nameofMethod) where T : class
    {
        return nameofMethod(instance);
    }
    
    // As static method
    public static string GetMethodName(Func nameofMethod) where T : class
    {
        return nameofMethod(default);
    }
    
    

    Usage:

    public class Car
    {
        public void Drive() { }
    }
    
    var car = new Car();
    
    string methodName1 = car.GetMethodName(c => nameof(c.Drive));
    
    var nullCar = new Car();
    
    string methodName2 = nullCar.GetMethodName(c => nameof(c.Drive));
    
    string methodName3 = GetMethodName(c => nameof(c.Drive));
    

提交回复
热议问题