2012-07-24 62 views
1

如何根據變量的內容調用方法基於變量內容的c#調用方法

ex。

String S = "Hello World"; 
String Format = "ToUpper()"; 

String sFormat = s.Format; 

resulting in "HELLO WORLD" 

這樣我可以在其他時間通過Format = "ToLower()"或格式=「刪除(1,4)」,這將刪除4個字符從位置1開始 - 在短我想調用任何字符串的方法的能力。

有人可以發佈一個完整的工作解決方案。

+0

你可以與反思這樣做很容易...但它不完全是碼最快位寫過。 – asawyer 2012-07-24 02:52:33

+0

看到這個答案: http://stackoverflow.com/questions/4629/how-can-i-read-the-properties-of-a-c-sharp-class-dynamically – David 2012-07-24 02:57:38

+1

真正的問題是;這是解決你的問題的最好方法嗎? – 2012-07-24 03:01:55

回答

1

解決方案的癥結要求您使用Reflection來定位所需的方法。這是一個簡單的例子,涵蓋你的sitaution;

private string DoFormat(string data, string format) 
{ 
    MethodInfo mi = typeof (string).GetMethod(format, new Type[0]); 
    if (null == mi) 
     throw new Exception(String.Format("Could not find method with name '{0}'", format)); 

    return mi.Invoke(data, null).ToString(); 
} 

您可以使該方法更通用,接受要調用的方法的參數,如下所示。請注意對方法的更改.GetMethod和.Invoke被調用以傳遞所需的參數。

private static string DoFormat(string data, string format, object[] parameters) 
{ 
    Type[] parameterTypes = (from p in parameters select p.GetType()).ToArray(); 

    MethodInfo mi = typeof(string).GetMethod(format, parameterTypes); 
    if (null == mi) 
     throw new Exception(String.Format("Could not find method with name '{0}'", format)); 

    return mi.Invoke(data, parameters).ToString(); 
} 
+0

您的解決方案適用於ToUpper或ToLower,但如何通過替換(1,4) – wadapav 2012-07-24 14:58:00

+0

請參閱上面的編輯。您需要調用GetMethod和Invoke的不同重載以將參數傳遞給「DoFormat」方法。 – 2012-07-24 21:59:38

0

爲什麼不只是使用方法本身。

Func<string, string> format = s = > s.ToUpper(); 

,然後你可以做

format = s = > s.ToLower(); 

否則你不得不去思考,這是不是安全,可能更慢。

+0

如果要使用的方法是外部指定的(例如,在配置文件中),則仍然需要某種方法將方法名稱轉換爲方法。 – 2012-07-24 02:55:41

+0

@RJLohan如果他不得不使用字符串,我仍然會使用枚舉來選擇正確的方法。 – 2012-07-24 02:57:24

0

您可以在這裏使用Reflection。看看MethodInfo課程。

0

這樣的東西可以工作,但我沒有編譯器在我面前驗證。

這樣使用它:

var result = someObject.CallParameterlessMethod("ToUpper"); 




public static class ObjectExtensionMethods 
{ 
    public static object CallParameterlessMethod(this object obj, string methodName) 
    { 
    var method = typeof(obj).GetMethod(methodName); 
    return method.Invoke(obj,null); 
    } 
} 
1

你可以用反射做到這一點,但代碼變得難以閱讀,類型安全消失。

C#提供了一個更好的機制來傳遞可執行代碼 - 即委託。

你可以做這樣的事情:

void ShowConverted(string str, Func<string,string> conv) { 
    Console.WriteLine("{0} -- {1}", str, conv(str)); 
} 

Func<string,string> strAction1 = (s) => s.ToUpper(); 
Func<string,string> strAction2 = (s) => s.ToLower(); 
ShowConverted("Hello, world!", stringAction1); 
ShowConverted("Hello, world!", stringAction2); 
1

您可以使用反射來從字符串類型拉ToLower將()方法。

string format = "Hello World"; 
    MethodInfo methodInfo = typeof(string).GetMethod("ToLower"); 
    string result = methodInfo.Invoke(format,null); 

我可能搞砸的語法有點