Tôi đang cố chuyển đổi một chuỗi thành lớp tương ứng của nó (ví dụ: "true" thành true
). Và tôi nhận được "TypeConverter không thể chuyển đổi từ System.String". Giá trị được chuyển là "true".TypeConverter không thể chuyển đổi từ System.String
Tôi có gọi phương thức không chính xác không?
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);
}
có thể trùng lặp: http://stackoverflow.com/questions/8625/generic-type-conversion-from-string – Adam