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?
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With