Las*_*vik 5 c# parsing type-conversion
我正在尝试将字符串转换为其对应的类(即"true" true).我得到"TypeConverter无法从System.String转换".传递的值是"true".
我是以错误的方式调用方法吗?
public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
Type type = typeof(T);
T ret = new T();
foreach (var keyValue in source)
{
type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value.ToString().TestParse<T>(), null);
}
return ret;
}
public static T TestParse<T>(this string value)
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
Run Code Online (Sandbox Code Playgroud)
问题是,T传递给TestParse方法的不是bool类型,而是要创建的类的类型.如果您将行更改为
public static bool TestParse(this string value)
{
return (bool)TypeDescriptor.GetConverter(typeof(bool)).ConvertFromString(value);
}
Run Code Online (Sandbox Code Playgroud)
它适用于布尔案,但显然不适用于其他情况.您需要通过反射获取要设置的属性的类型,并将其传递给TestParse方法.
public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
Type type = typeof(T);
T ret = new T();
foreach (var keyValue in source)
{
var propertyInfo = type.GetProperty(keyValue.Key);
propertyInfo.SetValue(ret, keyValue.Value.ToString().TestParse(propertyInfo.PropertyType), null);
}
return ret;
}
public static object TestParse(this string value, Type type)
{
return TypeDescriptor.GetConverter(type).ConvertFromString(value);
}
Run Code Online (Sandbox Code Playgroud)
我也会将TestParse方法从扩展方法更改为普通方法,因为它感觉有点奇怪
| 归档时间: |
|
| 查看次数: |
13166 次 |
| 最近记录: |