2013-02-28 100 views
0

我有以下代碼:從方法名稱字符串動態調用方法?

public string GetResponse() 
    { 
     string fileName = this.Page.Request.PathInfo; 
     fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1); 

     switch (fileName) 
     { 
      case "GetEmployees": 
       return GetEmployees(); 
      default: 
       return ""; 
     } 
    } 

    public string GetEmployees() 
    { 

我將有很多這樣的。他們都會返回一個字符串,並想知道是否有辦法避免切換案例。如果存在,如果方法不存在,是否有返回「未找到」的方法?

感謝

回答

1

使用反射來獲得方法:

public string GetResponse() 
{ 
    string fileName = this.Page.Request.PathInfo; 
    fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1); 

    MethodInfo method = this.GetType().GetMethod(fileName); 
    if (method == null) 
     throw new InvalidOperationException(
      string.Format("Unknown method {0}.", fileName)); 
    return (string) method.Invoke(this, new object[0]); 
} 

這是假定你所呼叫的方法將總是有0參數。如果它們具有不同數量的參數,則必須相應地調整傳遞給MethodInfo.Invoke()的參數數組。

GetMethod有幾個重載。此示例中的僅返回公共方法。如果你想檢索私有方法,你需要調用其中一個重載方法GetMethod來接受BindingFlags參數並傳遞BindingFlags.Private。

+0

當方法不存在時會發生什麼? – user2043533 2013-02-28 18:30:36

+0

您從GetMethod獲得空引用。你的代碼將不得不驗證這一點,並相應地處理缺失的方法。我會改變答案以反映(赦免雙關語)這一點。 – 2013-02-28 18:31:50

+0

非常感謝! – user2043533 2013-02-28 18:33:40

相關問題