C#动态选择调用某个指定函数的方法:
private void Btn_Execute_Click(object sender, EventArgs e)
{
if (T_Functions.Text.Length == 0)
{
MessageBox.Show("Pls choice function.");
return;
}
Type type = this.GetType();
MethodInfo mi = type.GetMethod(T_Functions.Text);
object[] objParams = null;
switch (T_Functions.Text)
{
case "TestFunction01":
objParams = null;
break;
case "TestFunction02":
if (T_Params.Text.Length == 0)
{
MessageBox.Show("This function need one param.");
return;
}
objParams = new object[1];
objParams[0] = T_Params.Text;
break;
}
T_Result.Text = (string)mi.Invoke(this, objParams);
}
public string TestFunction01()
{
return "TestFunction01";
}
public string TestFunction02(string sMsg)
{
return "TestFunction02 - " + sMsg;
}
其中,T_Functions.Text为一个ComboBox,可以选择两个函数,TestFunction01和TestFunction02
C#动态调用方法
本文介绍了一种在C#中动态选择并调用特定函数的方法。通过使用反射获取当前类型的方法,并根据ComboBox的选择来执行相应的函数。示例中包含了两个函数TestFunction01和TestFunction02,分别用于展示无参和带参数的情况。
4732

被折叠的 条评论
为什么被折叠?



