I'm trying to convert a string to its corresponding class (i.e. "true" to true
). And I get "TypeConverter cannot convert from System.String". The value passed is "true".
Am I calling the method in the wrong way?
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);
}
The problem is that the T
you pass to the TestParse
method is not the type bool but the type of the class you want to create. If you change the line to
public static bool TestParse(this string value)
{
return (bool)TypeDescriptor.GetConverter(typeof(bool)).ConvertFromString(value);
}
It works for the bool case but obviously not for other cases. You need to get the type of the property you want to set via reflection and pass it to the TestParse
method.
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);
}
I would also change the TestParse
method from an Extension Method to a normal method because it feels kinda weird
Do it as it was done in this answer:
return (T)Convert.ChangeType(value, typeof(T));
where T
is the target Type and value is of Type string
EDIT: this only works for IConvertible
implementers...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With