这个问题在这里已经有了答案:
Calling a function from a string in C#
(5 个回答)
去年关闭。
我有一个结构数组,其中包含可以运行的不同报告的详细信息。每个报告调用不同的方法,目前程序必须手动检查选定的报告值以专门调用适当的方法。
我想将方法名称存储在 struct-array 中,然后让程序在匹配时调用该方法。这可能吗?
目前:
if (this.cboSelectReport.Text == "Daily_Unload")
{
reportDailyUnload();
}
理想情况下:
if(this.cboSelectReport.Text == MyArray[i].Name)
{
something(MyArray[i].MethodName);
}
更新
我厌倦了下面的一些建议,但都没有奏效。他们没有工作可能是因为我的程序结构如何。
最佳答案
您可以使用反射来做到这一点,但 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});
更好的方法是根据您的方法定义一个委托(delegate),并将其存储在 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);
}
}
您可以使用基于
Action<T1,T2,...>
的预定义委托(delegate)类型,而不是定义自己的委托(delegate)类型。或 Func<T1,T2,R>
,取决于您需要从报告中返回值。
关于c# - 根据数组中包含的字符串值调用/调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9879332/