1.我们先定义三个方法
using System; namespace Testrun { public class Testclass { public void PrintTxt() { Console.WriteLine("void&noparameter"); } public void PrintTxt(int value1) { Console.WriteLine("void&1parameter:" + value1); } public string PrintTxt(int value1, int value2) { var resStr = "string&2parameter: " + value1 + ", " + value2; //Console.WriteLine(resStr); return resStr; } } }
2.调用的方式:
using System; using System.Reflection; namespace Testrun { class Program { static void Main(string[] args) { string strClass = "Testrun" + "." + "Testclass"; const string strMethod = "PrintTxt"; Type type = Type.GetType(strClass); if (type != null) { Object obj = Activator.CreateInstance(type); MethodInfo method = type.GetMethod(strMethod, new Type[] { }); object[] parameters = null; method.Invoke(obj, parameters); method = type.GetMethod(strMethod, new Type[] { typeof(int) }); parameters = new Object[] { 18 }; method.Invoke(obj, parameters); method = type.GetMethod(strMethod, new Type[] { typeof(int), typeof(int) }); parameters = new Object[] { 18, 2 }; var res = (string)method.Invoke(obj, parameters); Console.WriteLine(res); } } } }
3.运行结果
标签:Type,string,parameters,C#,type,int,方法,method,类名 From: https://www.cnblogs.com/yellow3gold/p/16979204.html