解决方案的症结要求您使用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();
}
你可以与反思这样做很容易...但它不完全是码最快位写过。 – asawyer 2012-07-24 02:52:33
看到这个答案: http://stackoverflow.com/questions/4629/how-can-i-read-the-properties-of-a-c-sharp-class-dynamically – David 2012-07-24 02:57:38
真正的问题是;这是解决你的问题的最好方法吗? – 2012-07-24 03:01:55