2011-12-22 30 views
5

Estoy tratando de convertir una cadena a su clase correspondiente (es decir, "verdadero" a true). Y obtengo "TypeConverter no se puede convertir de System.String". El valor pasado es "verdadero".TypeConverter no se puede convertir de System.String

¿Estoy llamando al método de la manera incorrecta?

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); 
} 
+0

posible duplicado de: http://stackoverflow.com/questions/8625/generic-type-conversion-from-string – Adam

Respuesta

6

El problema es que el T se pasa al método TestParse no es el tipo bool, pero el tipo de la clase que desea crear. Si cambia la línea a

public static bool TestParse(this string value) 
    { 
     return (bool)TypeDescriptor.GetConverter(typeof(bool)).ConvertFromString(value); 
    } 

Funciona para el caso bool, pero obviamente no para otros casos. Debe obtener el tipo de propiedad que desea establecer mediante reflexión y pasarlo al método 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); 
} 

que habría también cambiar el método TestParse de un método de extensión a un método normal porque se siente un poco extraño

+0

¡Impresionante! :) Muchas gracias y feliz Navidad! :) –

+0

feliz Navidad a ti también :) – kev

1

hacerlo como se hizo en this answer:

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

donde T es el tipo y el valor de destino son del tipo string
EDITAR: esto solo funciona para los implementadores IConvertible ...

Cuestiones relacionadas