Get the name of a method using an expression

后端 未结 6 1159
被撕碎了的回忆
被撕碎了的回忆 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:34

    The following is compatible with .NET 4.5:

    public static string MethodName(LambdaExpression expression)
    {
        var unaryExpression = (UnaryExpression)expression.Body;
        var methodCallExpression = (MethodCallExpression)unaryExpression.Operand;
        var methodCallObject = (ConstantExpression)methodCallExpression.Object;
        var methodInfo = (MethodInfo)methodCallObject.Value;
    
        return methodInfo.Name;
    }
    

    You can use it with expressions like x => x.DoSomething, however it would require some wrapping into generic methods for different types of methods.

    Here is a backwards-compatible version:

    private static bool IsNET45 = Type.GetType("System.Reflection.ReflectionContext", false) != null;
    
    public static string MethodName(LambdaExpression expression)
    {
        var unaryExpression = (UnaryExpression)expression.Body;
        var methodCallExpression = (MethodCallExpression)unaryExpression.Operand;
        if (IsNET45)
        {
            var methodCallObject = (ConstantExpression)methodCallExpression.Object;
            var methodInfo = (MethodInfo)methodCallObject.Value;
            return methodInfo.Name;
        }
        else
        {
            var methodInfoExpression = (ConstantExpression)methodCallExpression.Arguments.Last();
            var methodInfo = (MemberInfo)methodInfoExpression.Value;
            return methodInfo.Name;
        }
    }
    

    Check this sample code on Ideone. Note, that Ideone does not have .NET 4.5.

提交回复
热议问题