C#:通过类名和方法名调用方法
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; namespace Testrun { class Program { static void Main(string[] args) { string strClass = "Testrun" + "." + "Testclass"; const string strMethod = "PrintTxt"; var type = Type.GetType(strClass); if (type == null) return; var obj = Activator.CreateInstance(type); var method = type.GetMethod(strMethod, new Type[] { }); if (method != null) method.Invoke(obj, null); method = type.GetMethod(strMethod, new[] { typeof(int) }); var parameters = new object[] { 18 }; if (method != null) method.Invoke(obj, parameters); method = type.GetMethod(strMethod, new[] { typeof(int), typeof(int) }); parameters = new object[] { 18, 2 }; if (method != null) { var res = (string)method.Invoke(obj, parameters); Console.WriteLine(res); } } } }
3.运行结果