get methodinfo from a method reference C#
Slight adaptation of a previously posted answer, but this blog post seems to achieve what you're asking for; http://blog.functionalfun.net/2009/10/getting-methodinfo-of-generic-method.html
Sample usage would be as follows;
var methodInfo = SymbolExtensions.GetMethodInfo(() => Program.Main());
Original answer was to this question; https://stackoverflow.com/a/9132588/5827
You can use expression trees for non-static methods. Here is an example.
using System.Linq.Expressions;
using System.Reflection;
public static class MethodInfoHelper
{
public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> expression)
{
var member = expression.Body as MethodCallExpression;
if (member != null)
return member.Method;
throw new ArgumentException("Expression is not a method", "expression");
}
}
You would use it like this:
MethodInfo mi = MethodInfoHelper.GetMethodInfo<Program>(x => x.Test());
Console.WriteLine(mi.Name);
Test() is a member function declared in the Program class.
Use MemberExpression
and MemberInfo
instead if you want to support property getters and setters.
public class Foo
{
public void DoFoo()
{
Trace.WriteLine("DoFoo");
}
public static void DoStaticFoo()
{
Trace.WriteLine("DoStaticFoo");
}
}
And you can do something like this
MethodInfo GetMethodInfo(Action a)
{
return a.Method;
}
var foo = new Foo();
MethodInfo mi = GetMethodInfo(foo.DoFoo);
MethodInfo miStatic = GetMethodInfo(Foo.DoStaticFoo);
//do whatever you need with method info
Update
Per @Greg comment if you have some parameters to the methods, you can use Action<T>
, Action<T1, T2>
, Action<T1, T2, T3>
, or Func<T1>
, the inconvenience is that you will still need to write the overloads for GetMethodInfo
.