需求:100 個類別(login、register...),依參數 param 動態 new 並呼叫 exec(),避免大量 if-else。
public object CreateAndExecute(string className) {
// 1. 取得型別(假設在同一組件、命名空間 MyApp.Commands)
Type type = Type.GetType("MyApp.Commands." + className);
if (type == null) throw new ArgumentException("找不到類別: " + className);
// 2. 建立實例(無參建構子)
object instance = Activator.CreateInstance(type);
// 3. 取得並呼叫 exec 方法
MethodInfo method = type.GetMethod("exec");
if (method == null) throw new MissingMethodException("缺少 exec 方法");
return method.Invoke(instance, null);
}
public interface ICommand { void Execute(); }
// 所有命令類別實作 ICommand
public class LoginCommand : ICommand { public void Execute() { ... } }
// 反射建立後強制轉型
ICommand cmd = (ICommand)Activator.CreateInstance(type);
cmd.Execute(); // 編譯期型別安全
Type、MethodInfo、ConstructorInfo 避免重複反射查詢。Delegate.CreateDelegate 產生強型別委派,呼叫速度接近直接呼叫。反射是「依名稱動態建立」的標準解法,配合介面約束兼具彈性與安全。