TypeConverter cannot convert from System.String

I am trying to convert a string to the appropriate class (ie "true" in true). And I get "TypeConverter cannot convert from System.String". The past value is true.

Am I calling a method wrong?

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);
}
+5
source share
2 answers

The problem is that what Tyou pass to the method TestParseis not the type of bool, but the type of class that 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);
    }

bool, . , , 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);
}

TestParse ,

+6

, :

return (T)Convert.ChangeType(value, typeof(T));

T - , string
EDIT: IConvertible...

+1

All Articles