基于数组中包含的字符串值调用/调用方法

Joh*_*n M 4 c# methods .net-3.5

我有一个struct-array,其中包含可以运行的不同报告的详细信息.每个报告调用一个不同的方法,目前程序必须手动检查选定的报告值以专门调用适当的方法.

我想将方法​​名存储在struct-array中,然后让程序在匹配时调用该方法.这可能吗?

目前:

if (this.cboSelectReport.Text == "Daily_Unload")
{
   reportDailyUnload();
 }
Run Code Online (Sandbox Code Playgroud)

理想的情况是:

if(this.cboSelectReport.Text == MyArray[i].Name)
{
   something(MyArray[i].MethodName);
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

我厌倦了下面的一些建议,但没有一个有效.他们没有工作可能是因为我的程序结构如何.

das*_*ght 6

你可以使用反射来实现它,但IMO它太脆弱了:它会引入一个对你调用的方法名称的不可见依赖.

// 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});
Run Code Online (Sandbox Code Playgroud)

更好的方法是根据您的方法定义委托,并将其存储在struct/class而不是方法名称中.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

而不是定义自己的委托类型,可以使用基于预定义的人Action<T1,T2,...>或者Func<T1,T2,R>,根据您的需要从报告中返回值.