一、反射的实现
using System;
using System.Reflection;
using System.Threading.Tasks;public class Calculator
{public int Add(int a, int b){return a + b;}public int Subtract(int a, int b){return a - b;}public int Multiply(int a, int b){return a * b;}public double Divide(int a, int b){if (b == 0) throw new DivideByZeroException();return (double)a / b;}
}class Program
{static void Main(){// 创建Calculator实例var calc = new Calculator();// 定义要调用的方法名和参数string methodName = "Multiply"; // 可以是"Subtract", "Multiply", "Divide"object[] parameters = new object[] { 5, 3 };// 获取Calculator类型Type type = calc.GetType();try{// 查找方法MethodInfo methodInfo = type.GetMethod(methodName);if (methodInfo != null){// 调用方法并输出结果var result = methodInfo.Invoke(calc, parameters);Console.WriteLine($"方法{methodName}的结果是: {result}");}else{Console.WriteLine("未找到该方法");}}catch (Exception ex){Console.WriteLine(ex.ToString());}}
}
二、思考:让字符串决定方法的调用
方法 | 优点 | 缺点 | 适用场景 |
反射 | 灵活,动态调用 | 慢,易出错 | 动态调用未知方法 |
委托字典 | 快,可控 | 需预定义 | 固定方法集合快速调用 |
工厂模式 | 可扩展,解耦 | 结构复杂 | 对象创建逻辑统一管理 |
表达式树 | 编译后快,灵活 | 复杂,难写 | 动态构建逻辑 |