2008-12-26 9 views
31

Tengo el siguiente código:función de conversión genérica para trabajar con GUID

public static T ParameterFetchValue<T>(string parameterKey) 
{ 
    Parameter result = null; 

    result = ParameterRepository.FetchParameter(parameterKey); 

    return (T)Convert.ChangeType(result.CurrentValue, typeof(T), CultureInfo.InvariantCulture); 
} 

El tipo de result.CurrentValue es cadena. Me gustaría ser capaz de convertirlo en Guid pero aparece el error:

Invalid cast from System.String to System.Guid

Esto funciona perfectamente con los tipos de datos primitivos.
¿Hay alguna manera de hacer que esto funcione para tipos de datos no primitivos?

Respuesta

82

¿Qué tal:

T t = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(text); 

funciona bien para Guid y la mayoría de otros tipos.

+4

tener cuidado con el uso de ConvertFromInvariantString. Si su tipo es DateTime y tiene formatos de fecha internacionales, esto explotará. Acabo de rastrear un error realmente difícil de encontrar basado en esta respuesta. –

+0

@DPeden de hecho, deben coincidir: mi uso aquí fue invariante asumiendo que los datos serializados generalmente deberían estar en un formato invariante –

+0

Sí, acordó. Seguí votando tu respuesta, ya que es muy útil. Solo señalo este potencial para los demás, ya que me quemó. –

0

intenta esto:

public object ChangeType(object value, Type type) 
    { 
     if (value == null && type.IsGenericType) return Activator.CreateInstance(type); 
     if (value == null) return null; 
     if (type == value.GetType()) return value; 
     if (type.IsEnum) 
     { 
      if (value is string) 
       return Enum.Parse(type, value as string); 
      else 
       return Enum.ToObject(type, value); 
     } 
     if (!type.IsInterface && type.IsGenericType) 
     { 
      Type innerType = type.GetGenericArguments()[0]; 
      object innerValue = ChangeType(value, innerType); 
      return Activator.CreateInstance(type, new object[] { innerValue }); 
     } 
     if (value is string && type == typeof(Guid)) return new Guid(value as string); 
     if (value is string && type == typeof(Version)) return new Version(value as string); 
     if (!(value is IConvertible)) return value; 
     return Convert.ChangeType(value, type); 
    } 
Cuestiones relacionadas