首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 依字串動態建立物件並呼叫方法:反射完整範例

     編輯:程式設計疑難解答

需求: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 產生強型別委派,呼叫速度接近直接呼叫。

反射是「依名稱動態建立」的標準解法,配合介面約束兼具彈性與安全。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved