【问题标题】:How can I create a MethodInfo from an Action delegate如何从 Action 委托创建 MethodInfo
【发布时间】:2011-02-04 07:41:12
【问题描述】:

我正在尝试开发一个 NUnit 插件,它可以从包含Action 委托列表的对象动态地将测试方法添加到套件中。问题是 NUnit 似乎严重依赖反射来完成工作。因此,似乎没有简单的方法可以将我的Actions 直接添加到套件中。

我必须改为添加 MethodInfo 对象。这通常可以工作,但Action 代表是匿名的,因此我必须构建类型和方法来完成此操作。我需要找到一种更简单的方法来做到这一点,而无需使用Emit。有谁知道如何从 Action 委托轻松创建 MethodInfo 实例?

【问题讨论】:

    标签: c# .net reflection nunit-addins


    【解决方案1】:

    你试过 Action 的 Method 属性吗?我的意思是:

    MethodInfo GetMI(Action a)
    {
        return a.Method;
    }
    

    【讨论】:

      【解决方案2】:

      您不需要“创建”MethodInfo,您可以从委托中检索它:

      Action action = () => Console.WriteLine("Hello world !");
      MethodInfo method = action.Method
      

      【讨论】:

      • +1,你和费德都答对了。我接受了他的,因为领带属于他的代表少两位数的人。 :)
      【解决方案3】:
      MethodInvoker CvtActionToMI(Action d)
      {
         MethodInvoker converted = delegate { d(); };
         return converted;
      }
      

      对不起,不是你想要的。

      请注意,所有代表都是多播的,因此不能保证是唯一的MethodInfo。这将为您提供所有这些:

      MethodInfo[] CvtActionToMIArray(Action d)
      {
         if (d == null) return new MethodInfo[0];
         Delegate[] targets = d.GetInvocationList();
         MethodInfo[] converted = new MethodInfo[targets.Length];
         for( int i = 0; i < targets.Length; ++i ) converted[i] = targets[i].Method;
         return converted;
      }
      

      您会丢失有关目标对象的信息(取消代理),所以我不希望 NUnit 能够在之后成功调用任何东西。

      【讨论】:

      • 对不起,我看到MethodInfo的时候想到的是MethodInvoker。
      • +1(让你回到零)。事实证明,d.Method 是我所需要的。它确实在 NUnit 中工作,虽然命名很时髦。我必须创建自己的测试类来解决这个问题。
      猜你喜欢
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 2015-02-09
      • 2017-07-02
      相关资源
      最近更新 更多