demo如下:
using System.Reflection;
using System;public class Program
{public class Calculator{public int Add(int a, int b){return a + b;}}public class Student{public string Name { get; set; }}public class Example{// 泛型方法public string GenericMethod<T>(string name) where T : class, new(){return $"调用了泛型方法,入参是:{typeof(T).Name}类,参数{name}";}}public static void Main(){// 01获取类型var calculator = new Calculator();Type calcType = typeof(Calculator);// 02获取方法(根据字符串获取)MethodInfo addMethod = calcType.GetMethod("Add");// 03准备入参object[] parameters = new object[] { 5, 10 };// 04使用 Invoke 调用方法并获取返回值int result = (int)addMethod.Invoke(calculator, parameters);// 输出结果Console.WriteLine($"Result: {result}");// 01获取 Example 类型var example = new Example();Type exampleType = typeof(Example);// 02获取泛型方法 GenericMethodMethodInfo generalMethod = exampleType.GetMethod("GenericMethod");// 构建泛型方法:GenericMethod<Student>(string name)MethodInfo genericMethod = generalMethod.MakeGenericMethod(typeof(Student));//多个泛型入参参考:MethodInfo genericMethod = generalMethod.MakeGenericMethod(typeof(Student), typeof(Teacher));// 03准备参数object[] parameters2 = new object[] { "John Doe" };// 04调用泛型方法并获取返回值string result2 = (string)genericMethod.Invoke(example, parameters2);// 05输出返回值的类型Console.WriteLine($"Result2: {result2}");}
}
输出结果:
Result: 15
Result2: 调用了泛型方法,入参是:Student类,参数John Doe
总结: