如何从方法符号中获取MethodInfo

Ron*_*rby 6 .net c# reflection

是否可以从方法符号中获取MethodInfo对象?

所以同样如下:

typeof(SomeClassSymbol) // this gets you a Type object
Run Code Online (Sandbox Code Playgroud)

这是我想要做的:

public class Meatwad
{
    MethodInfo method;

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

    public void SomeMethod() { }

}
Run Code Online (Sandbox Code Playgroud)

我怎么能实现ReflectionThingy.GetMethodInfo?鉴于这甚至可能,重载方法怎么样?

svi*_*ick 8

代表MethodInfo在他们的Method财产中包含您想要的.所以你的帮助方法可以很简单:

MethodInfo GetMethodInfo(Delegate d)
{
    return d.Method;
}
Run Code Online (Sandbox Code Playgroud)

您无法直接从方法组转换为Delegate.但你可以使用演员阵容.例如:

GetMethodInfo((Action)Console.WriteLine)
Run Code Online (Sandbox Code Playgroud)

请注意,如果您尝试将其与usr的解决方案混合使用,则无法使用此功能.例如

GetMethodInfo((Action)(() => Console.WriteLine()))
Run Code Online (Sandbox Code Playgroud)

将返回MethodInfo生成的匿名方法,而不是Console.WriteLine().

  • 到目前为止,我最喜欢这个,但有趣的是,您可以仅使用方法符号构造一个动作,并从动作的 Method 属性中获取 MethodInfo。这就是我最终想要学习如何做的。如果我有时间,我将反编译 Action 以查看发生了什么。 (2认同)

usr*_*usr 3

这在 C# 中是不可能直接实现的。但你可以自己构建这个:

    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*/);
    }
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

var methName = MemberInfo(() => SomeMethod()).MethodName;
Run Code Online (Sandbox Code Playgroud)

这将为您提供编译时安全性。但性能不会很好。

  • @usr 当性能成为问题时,通过使用它来初始化静态只读对象,而不是每次都调用函数,可以轻松解决它。 (2认同)