【问题标题】:How to get MethodInfo from a method symbol [duplicate]如何从方法符号中获取 MethodInfo [重复]
【发布时间】:2012-02-27 17:45:30
【问题描述】:

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

因此与以下内容相同:

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

这是我想做的:

public class Meatwad
{
    MethodInfo method;

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

    public void SomeMethod() { }

}

如何实现 ReflectionThingy.GetMethodInfo?鉴于这甚至是可能的,那么重载方法呢?

【问题讨论】:

标签: c# .net reflection


【解决方案1】:

代表在其Method property 中包含您想要的MethodInfo。所以你的辅助方法可以很简单:

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

您不能直接从方法组转换为Delegate。但是您可以为此使用演员表。例如:

GetMethodInfo((Action)Console.WriteLine)

请注意,如果您尝试将它与类似 usr 的解决方案混合使用,这将不起作用。例如

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

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

【讨论】:

  • 到目前为止我最喜欢这个,但有趣的是你可以只用方法符号构造一个动作,并从动作的方法属性中获取方法信息。这最终就是我试图学习如何去做的事情。如果我有时间,我会反编译 Action 看看发生了什么。
【解决方案2】:

这在 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*/);
    }

并像这样使用它:

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

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

【讨论】:

  • 为什么你的方法有一个从未使用过的参数?
  • 我从一个有 200 LOC 的助手类中复制了这个。我只是想给出它的要点。请将此视为伪代码 ;-) 不过,这个想法将完全有效。
  • @usr 当性能成为问题时,使用它来初始化静态只读对象很容易解决,而不是每次都调用你的函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 2014-09-28
  • 2014-04-02
相关资源
最近更新 更多