c# - 运行类 C# 中的所有方法

标签 c# .net

<分区>

我有一个包含 200 多个函数的类。我需要一个函数来运行类中的所有方法。

所有函数都返回void,并且不带任何参数。

这是我目前拥有的:

public void runAllFunctions()
{
        var methods = typeof(win10).GetMethods(BindingFlags.Public | BindingFlags.Instance);
        object[] parameters = null;
        foreach (var method in methods)
        {
            if (method.Name.StartsWith("WN10"))
            {
                method.Invoke(null, parameters);
            }
        }
    }

使用这段代码,我得到错误“非静态方法需要一个目标”

如何运行所有方法?

最佳答案

你必须提供win10实例;如果 runAllFunctionswin10 的方法:

  public void runAllFunctions() {
    var methods = GetType()
      .GetMethods(BindingFlags.Public | BindingFlags.Instance)
      .Where(item => item.Name.StartsWith("WN10"));

    foreach (var method in methods)
      method.Invoke(this, new Object[0]); // please, notice "this"
  }  

如果 runAllFunctions 不是 win10 的方法:

  public void runAllFunctions() {
    win10 instance = new win10(); //TODO: put right constructor here

    var methods = instance
      .GetType()
      .GetMethods(BindingFlags.Public | BindingFlags.Instance)
      .Where(item => item.Name.StartsWith("WN10"));

    foreach (var method in methods)
      method.Invoke(instance, new Object[0]);
  }  

关于c# - 运行类 C# 中的所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39108677/

相关文章:

c# - MvvmCross Android EditText 绑定(bind)不更新屏幕

c# - 在 C# TabControl 上隐藏选项卡标题

c# - 在 C# 中查找质数

c# - 将字符串传递给接收 Action 的函数

c# - 使用 WPF 打开一个文本文件

c# - C#中VB6中ObjPtr的等效(功能)?

c# - 打印没有预览的 ReportViewer

c# - Azure 服务总线将消息添加到队列的速度太快

.net - ASP.Net Webforms 和 ASP.Net MVC 是基于组件还是基于 Action ?

c# - 什么是 ObjectFactory.Inject 在 StructureMap 3.0 中的等价物