有时为了不同情况下调用不同函数或者不同情况下调用函数的不同执行顺序,需要用到Invoke来绑定函数的定义,为了更好的理解这个绑定的使用,我大概简略地写了一个简单的test程序(C#),仅供参考,程序难免会有纰漏,欢迎指正。
using System.Reflection;
namespace testInvoke
{
public class testInvoke
{
private DataTable GetProcess(<某类型> Type)
{
DataTable dtProcess = new DataTable();
DataColumn col1 = new DataColumn("ADAPTERNAME");//函数名
DataColumn col2 = new DataColumn("ADAPTERPARAM");//函数所需参数
dtProcess.Columns.Add(col1);
dtProcess.Columns.Add(col2);
if (Type == ****)
{
dtProcess.Rows.Add(new Object[] { "Method1", null });
dtProcess.Rows.Add(new Object[] { "Method2", null });
dtProcess.Rows.Add(new Object[] { "Method3", null });
}
if(Type ==*****)
{
//其他Type时的dtProcess填充
}
private void RunProcess()
{
<类型> type;
//get Type
** type=*******;
DataTable dtProcess=GetProcess(type);
foreach (DataRow dr in dtProcess.Rows)
{
InvokeMethod(dr["ADAPTERNAME"].ToString(),dr["ADAPTERPARAM"]);
}
}
private void InvokeMethod(String name, String para)
{
MethodInfo m;
m = this.GetType().GetMethod(name, BindingFlags.Public | BindingFlags.Instance);
if (m.GetParameters().Length < 1)
m.Invoke(this, null);
else
m.Invoke(this, new Object[] { para });
}
Public void Method1()
{
/略
}
Public void Method2()
{
/略
}
Public void Method3()
{
/略
}
///others
}
}