为了账号安全,请及时绑定邮箱和手机立即绑定

用反射调用静态方法

用反射调用静态方法

C#
杨__羊羊 2019-11-15 21:03:15
我在命名空间中有几个静态类,mySolution.Macros例如static class Indent{         public static void Run(){         // implementation     }     // other helper methods}所以我的问题是,在反射的帮助下如何调用这些方法?如果方法不是静态的,那么我可以做些类似的事情: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);}我想让我的课保持静态。如何使用静态方法执行类似的操作?简而言之,我想从名称空间mySolution.Macros中的所有静态类中调用所有Run方法。C# 反射 动态
查看完整描述

3 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

正如MethodInfo.Invoke的文档所述,静态方法将忽略第一个参数,因此您可以仅传递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);


查看完整回答
反对 回复 2019-11-15
  • 3 回答
  • 0 关注
  • 769 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信