Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MethodInfo from a method symbol [duplicate]

Is it possible to get a MethodInfo object from a method symbol?

So in the same vein as:

typeof(SomeClassSymbol) // this gets you a Type object

Here is what I want to do:

public class Meatwad
{
    MethodInfo method;

    public Meatwad()
    {
        method = ReflectionThingy.GetMethodInfo(SomeMethod);
    }

    public void SomeMethod() { }

}

How could I implement ReflectionThingy.GetMethodInfo? Given this is even possible at all, what about overloaded methods?

like image 699
Ronnie Overby Avatar asked Feb 27 '12 17:02

Ronnie Overby


2 Answers

Delegates contain the MethodInfo you want in their Method property. So your helper method could be as simple as:

MethodInfo GetMethodInfo(Delegate d)
{
    return d.Method;
}

You cannot convert directly from a method group to Delegate. But you can use a cast for that. E.g.:

GetMethodInfo((Action)Console.WriteLine)

Be aware that this won't work if you try to mix it with something like usr's solution. For example

GetMethodInfo((Action)(() => Console.WriteLine()))

will return the MethodInfo for the generated anonymous method, not for Console.WriteLine().

like image 185
svick Avatar answered Oct 14 '22 22:10

svick


This is not possible in C# directly. But you can build this yourself:

    static MemberInfo MemberInfoCore(Expression body, ParameterExpression param)
    {
        if (body.NodeType == ExpressionType.MemberAccess)
        {
            var bodyMemberAccess = (MemberExpression)body;
            return bodyMemberAccess.Member;
        }
        else if (body.NodeType == ExpressionType.Call)
        {
            var bodyMemberAccess = (MethodCallExpression)body;
            return bodyMemberAccess.Method;
        }
        else throw new NotSupportedException();
    }

    public static MemberInfo MemberInfo<T1>(Expression<Func<T1>> memberSelectionExpression)
    {
        if (memberSelectionExpression == null) throw new ArgumentNullException("memberSelectionExpression");
        return MemberInfoCore(memberSelectionExpression.Body, null/*param*/);
    }

And use it like this:

var methName = MemberInfo(() => SomeMethod()).MethodName;

That will provide you compile-time safety. Performance will not be good though.

like image 37
usr Avatar answered Oct 14 '22 21:10

usr