How can I get the name of a method from an expression tree?

.net c# expression-trees linq reflection

Question

I'm attempting to use the next pattern function:

MethodInfo GetMethod(      
  Expression<Func<TTarget, EventHandler<TEventArgs>>> method)

If needed, I may provide a TTarget instance.

The intended use is:

public static void Main(string[] args)
{
    var methodInfo = GetMethod<Program, EventArgs>(t => t.Method);
    Console.WriteLine("Hello, world!");
}

private void Method(object sender, EventArgs e)
{
}

What I've so far attempted is as follows:

private static MethodInfo GetMethod(TTarget target, Expression<Func<TTarget, EventHandler<TEventArgs>>> method)
{
  var lambda = method as LambdaExpression;
  var body = lambda.Body as UnaryExpression;
  var call = body.Operand as MethodCallExpression;
  var mInfo = call.Method as MethodInfo;

  Console.WriteLine(mInfo);

  throw new NotImplementedException();
}

It prints:

System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.Met hodInfo)

1
7
1/26/2012 9:05:12 AM

Accepted Answer

You have reached halfway. View 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 to get the method name, use the following code.

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 clarifies your query.

6
1/26/2012 8:42:36 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow