基于数组中包含的字符串值调用/调用方法 [英] Call/Invoke a method based on a string value contained in an array

查看:148
本文介绍了基于数组中包含的字符串值调用/调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构数组,其中包含可以运行的不同报告的详细信息。每个报告调用一个不同的方法,当前程序必须手动检查所选的报告值以专门调用适当的方法。

I have a struct-array that contains details of different reports that can be run. Each report calls a different method and currently the program has to manually check the selected report value to specifically call the appropriate method.

我想将方法​​名称存储在struct-array中,然后让程序在匹配时调用该方法。

I would like to store the method name in the struct-array and then have program invoke that method when there is match. Is this possible?

当前:

if (this.cboSelectReport.Text == "Daily_Unload")
{
   reportDailyUnload();
 }

理想情况:

if(this.cboSelectReport.Text == MyArray[i].Name)
{
   something(MyArray[i].MethodName);
}

更新

我厌倦了下面的许多建议,但没有一个起作用。

I tired a number of the suggestions below and none of them worked. They didn't work probably due to how I have my program structured.

推荐答案

您可以使用 reflection ,但IMO太脆弱了:它对您调用的方法名称引入了不可见的依赖关系。

You can do it using reflection, but IMO it is too fragile: it introduces an invisible dependency on the name of the method that you call.

// Assuming that the method is static, you can access it like this:
var namedReportMethod = "MyReport1";
var reportMethod = typeof(ReporterClass).GetMethod(namedReportMethod);
var res = reportMethod.Invoke(null, new object[] {reportArg1, reportArg2});

更好的方法是根据您的方法定义委托

A better approach would be to define a delegate based on your method, and store it in the struct/class instead of the method name.

delegate void ReportDelegate(int param1, string param2);

class Runner {
    public static void RunReport(ReportDelegate rd) {
        rd(1, "hello");
    }
}

class Test {
    static void TestReport(int a, string b) {
        // ....
    }
    public static void Main(string[] args) {
        Runner.RunReport(TestReport);
    }
}

除了定义自己的委托类型,您还可以使用基于 Action< T1,T2,...> Func< T1,T2,R> ,具体取决于您需要从报告中返回值。

Instead of defining your own delegate types, you can use pre-defined ones based on Action<T1,T2,...> or Func<T1,T2,R>, depending on your need to return values from the reports.

这篇关于基于数组中包含的字符串值调用/调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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