c# - 根据数组中包含的字符串值调用/调用方法

标签 c# .net-3.5 methods

这个问题在这里已经有了答案:





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/

相关文章:

c# - 如何在不更改签名的情况下将同步方法转换为异步方法

c# - 需要 .NET 串行端口帮助,主要是在多个 "packets"中接收到的数据

visual-studio-2010 - 如何使用 msbuild 引导 .NET 3.5 SP1?按照找到的说明不起作用

c# - 是否可以从另一个表单触发点击事件?

python - 使用实例属性作为方法的参数

swift - 下标使用方法的额外优势是什么

c# - 替换字符串中除模式外的所有字母数字字符

c# - 如何确定哪个版本的Windows?

java - catch block 方法中的递归调用返回值

c# - 具有混合条件的 LINQ to SQL 复杂连接