您的位置:首页 > 其它

将字符串转化为某种类型

2014-05-15 09:56 113 查看
//将字符串转化为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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: