One, using InvokeMember
Idea: Call the InvokeMember method on the type's object, pass the object on which you want to invoke the method, and specify BindingFlags as InvokeMethod. Depending on the method signature, you may also need to pass parameters.
Examples (for common methods and calls to static methods):
#region 动态调用方法——使用InvokeMember对一般方法的调用 //Type t = typeof(Calculator); //Calculator c = new Calculator(1, 2); //int result = (int)t.InvokeMember("Add", BindingFlags.InvokeMethod, null, c, null); //Console.WriteLine(result); #endregion
#region 动态调用方法——使用InvokeMember对静态含参数方法的调用 //object[] paramas = { 6, 9 }; //Type t = typeof(Calculator); //t.InvokeMember("Add", BindingFlags.InvokeMethod, null, t, paramas);//静态方法不是基于某个具体的类型实例,而是类型本身。方法参数还是以object数组传入的 #endregion
Second, use Methodinfo.invoke
Use idea: Get the method object that you want to call, that is, the MethodInfo object, and then call the Invoke method on the object by using the GetMethod method of the Type object. Depending on the method signature, you may also need to pass parameters.
#region 动态调用方法——使用MethodInfo.Invoke调用方法 typeof(Calculator); new Calculator(34); MethodInfo mi = t.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); null#endregion
In fact, sometimes depending on the method name call method is very convenient, is the reflection of the performance of the problem has not been measured, said performance is not good, but how much impact, to explain?
. net--Dynamic Call method