Extract method name from expression tree?

后端 未结 1 342
旧巷少年郎
旧巷少年郎 2020-12-10 16:21

I am trying to implement the following pattern function:

MethodInfo GetMethod(      
  Expression>>          


        
相关标签:
1条回答
  • 2020-12-10 17:18

    You're half way there. Look at the code below

    public static void Main(string[] args)
    {
        var program = new Program();
        var methodInfo = GetMethod<Program, EventArgs>(()=> program.Method);
        Console.WriteLine(methodInfo.Name);
    }
    

    And use the following code to get the method name.

    static MethodInfo GetMethod<TTarget, TEventArgs>(Expression<Func<EventHandler<TEventArgs>>> method) where TEventArgs:EventArgs
    {
        var convert = method.Body as UnaryExpression;
        var methodCall = (convert.Operand as MethodCallExpression);
        if (methodCall != null && methodCall.Arguments.Count>2 && methodCall.Arguments[2] is ConstantExpression)
        {
            var methodInfo = (methodCall.Arguments[2]as ConstantExpression).Value as MethodInfo;
            return methodInfo;
        }
        return null;
    }
    

    I hope this answers your question.

    0 讨论(0)
提交回复
热议问题