How to get MethodInfo from a method symbol

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

So, in the same spirit 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 can I implement ReflectionThingy.GetMethodInfo? Given this, it’s even possible at all, but what about overloaded methods?

+6
source share
2 answers

Delegates contain the MethodInfo that you want in your Method property . Thus, your helper method may be as simple as:

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

You cannot convert directly from a group of methods to Delegate . But you can use a throw for this. For instance:.

 GetMethodInfo((Action)Console.WriteLine) 

Remember that this will not work if you try to mix it with something like a usr solution. for instance

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

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

+7
source

This is not possible in C # directly. But you can build it 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 as follows:

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

This will ensure you compile time security. However, performance will not be good.

+2
source

Source: https://habr.com/ru/post/909470/


All Articles