将字符串转化为某种类型
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;
}
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;
}
相关文章推荐
- 将字符串转化为某种类型
- 字符串转化成DATE类型
- VC Afx全局函数 数据类型 字符串转化函数
- 字符串类型的Unicode码转化为中文
- 各种字符串类型 string和wstring之间的转化
- VC Afx全局函数 数据类型 字符串转化函数
- C++/CLI 中字符串类型的转化: 把System::String转化为std::string
- 初始加载时把字符串,也就是""转化为int类型
- 将未指定格式的日期字符串转化成java.util.Date类型日期对象
- js字符串怎么样转化为日期类型
- 字符串与整型数的相互类型转化-atoi和itoa的简单写法~
- javascript--转化字符串为日期类型
- 关于C#中货币类型和数值类型、字符串类型的转化和在DataGridView中的显示问题:
- 把字符串转化成CTime类型
- Afx全局函数 数据类型 字符串转化函数
- SqlServer 中Binary类型的数据如何转化为字符串
- js:字符串类型快速转化成数字类型和数字类型快速转化为字符串类型
- Afx全局函数 数据类型 字符串转化函数
- IEEE 16进制字符串转化为double类型
- VC Afx全局函数 数据类型 字符串转化函数