//将字符串转化为type型.
private object parse(string s, Type t)
{
//如果字符串是一个string,直接返回.
if (t.IsAssignableFrom(typeof(string))) return s;
//如果字符串是一个数组,那么将其解析为数组并返回.
if (t.IsArray) return parseArray(s, t);
//构造并调用tpe的Parse方法.
BindingFlags flags = BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase | BindingFlags.Public;
MethodInfo parseMethod = t.GetMethod("Parse", flags, null, new Type[] { typeof(string) }, null);
if (parseMethod != null && parseMethod.ReturnType == t)
{
return parseMethod.Invoke(null, new object[] { s });
}
else
{
throw new ApplicationException("Can‘t parse " + t.FullName + " because it doesn‘t have a static Parse() method");
}
}
//将字符串转化为某种类型的数组.
private object[] parseArray(string s, Type arrayType)
{
string[] strings = s.Split(new char[] { ‘,‘ });
object[] result = new object[strings.Length];
for (int i = 0; i < strings.Length; i++)
{
result[i] = parse(strings[i], arrayType.GetElementType());
}
return result;
}
原文地址:http://www.cnblogs.com/robyn/p/3729321.html