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