将字符串转化为某种类型
2011-11-18 09:57
99 查看
//将字符串转化为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;
}
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;
}
相关文章推荐
- 将字符串转化为某种类型
- IOS 获取系统版本字符串,并且转化成float类型
- IEEE 16进制字符串转化为double类型
- jsp从固定类型的字符串中取出多个数值并转化为float型
- 页面提交表单Form中的字符串数据转化为指定类型
- C语言:将16进制字符串转化为int类型值
- C++/CLI 中字符串类型的转化: 把System::String转化为std::string
- Date类型与格式字符串、毫秒的转化
- C#中货币类型和数值类型、字符串类型的转化
- 把jason字符串转化为标注的data(responseObject)类型
- 将泛型为String类型的集合或String类型的数组转化为逗号间隔字符串形式
- 将未指定格式的日期字符串转化成java.util.Date类型日期对象
- C++/CLI 中字符串类型的转化: 把std::string转化为System::String
- 将科学计数法转化为常规格式再转化为字符串类型(String)
- 将clob数据类型转化为String类型(在json字符串赋值时候)
- 3.利用SimpleDateFormat()把字符串格式的时间转化为Date类型的时间
- c++基本类型&&&c++string与c风格字符串的相互转化
- Java中关于Json对象类型和字符串类型之间互相转化的问题
- JS 字符串转化为时间类型
- 再谈如何以最简单的方法将泛型为String类型的集合或String类型的数组转化为逗号间隔字符串形式