[英]c# call method based on contents of a variable
如何根據變量的內容調用方法
恩。
String S = "Hello World";
String Format = "ToUpper()";
String sFormat = s.Format;
resulting in "HELLO WORLD"
這樣我可以在其他時間傳遞Format = "ToLower()"
或Format =“Remove(1,4)”,這將刪除從pos 1開始的4個字符 - 簡而言之,我希望能夠調用任何字符串方法。
有人可以發布完整的工作解決方案。
解決方案的關鍵要求您使用Reflection來定位所需的方法。 這是一個涵蓋您的情況的簡單示例;
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();
}
您可以使用反射執行此操作,但代碼變得難以閱讀,並且類型安全性消失。
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);
您可以使用反射從字符串類型中提取ToLower()方法。
string format = "Hello World";
MethodInfo methodInfo = typeof(string).GetMethod("ToLower");
string result = methodInfo.Invoke(format,null);
我可能搞砸了一點語法
為什么不直接使用方法本身。
Func<string, string> format = s = > s.ToUpper();
然后你就可以做到
format = s = > s.ToLower();
否則你必須使用Reflection,這不安全且可能更慢。
你可以在這里使用Reflection。 看一下MethodInfo
類。
這樣的東西可行,但我沒有在我面前編譯驗證。
使用它像:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.