呼叫与反思静态方法 [英] Call static method with reflection

查看:116
本文介绍了呼叫与反思静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个静态类命名空间中的 mySolution.Macros

I have several static classes in the namespace mySolution.Macros such as

static class Indent{    
     public static void Run(){
         // implementation
     }
     // other helper methods
}

所以我的问题是,如何将可调用的写照吗?帮助那些方法

如果方法哪里都不是静态的话,我可以做类似:

If the methods where NOT to be static then I could do something like:

var macroClasses = Assembly.GetExecutingAssembly().GetTypes().Where( x => x.Namespace.ToUpper().Contains("MACRO") );

foreach (var tempClass in macroClasses)
{
   var curInsance = Activator.CreateInstance(tempClass);
   // I know have an instance of a macro and will be able to run it

   // using reflection I will be able to run the method as:
   curInsance.GetType().GetMethod("Run").Invoke(curInsance, null);
}

我喜欢让我类的静态。我如何能做到用静态方法相似的地方?

I will like to keep my classes static. How will I be able to do something similar with static methods?

总之我会想调用的所有运行方式从所有的静态类是在命名空间mySolution.Macros。

In short I will like to call all the Run methods from all the static classes that are in the namespace mySolution.Macros.

推荐答案

至于MethodInfo.Invoke的文档状态,第一个参数是静态方法忽略,所以你可以只传递null。

As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.

foreach (var tempClass in macroClasses)
{
   // using reflection I will be able to run the method as:
   tempClass.GetMethod("Run").Invoke(null, null);
}

由于评论指出的那样,你可能希望确保调用 GetMethod 时,方法是静态的:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

这篇关于呼叫与反思静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆