2012-08-24 11 views
6

Tengo los siguientes métodos de extensión para cadenas para poder hacer esto ("true").As<bool>(false) Especialmente para booleanos usará AsBool() para hacer algunas conversiones personalizadas. De alguna manera no puedo convertir de T a Bool y viceversa. Lo hice funcionar usando el siguiente código, pero parece un poco exagerado.Transmitir T a bool y viceversa

Es sobre esta línea:
(T)Convert.ChangeType(AsBool(value, Convert.ToBoolean(fallbackValue)), typeof(T))
Prefiero usar los siguientes, pero no se compilará:
(T)AsBool(value, (bool)fallbackValue), typeof(T))

Me estoy perdiendo algo o es el camino más corto para ir ?

public static T As<T>(this string value) 
    { 
     return As<T>(value, default(T)); 
    } 
    public static T As<T>(this string value, T fallbackValue) 
    { 
     if (typeof(T) == typeof(bool)) 
     { 
      return (T)Convert.ChangeType(AsBool(value, 
               Convert.ToBoolean(fallbackValue)), 
               typeof(T)); 
     } 
     T result = default(T); 
     if (String.IsNullOrEmpty(value)) 
      return fallbackValue; 
     try 
     { 
      var underlyingType = Nullable.GetUnderlyingType(typeof(T)); 
      if (underlyingType == null) 
       result = (T)Convert.ChangeType(value, typeof(T)); 
      else if (underlyingType == typeof(bool)) 
       result = (T)Convert.ChangeType(AsBool(value, 
               Convert.ToBoolean(fallbackValue)), 
               typeof(T)); 
      else 
       result = (T)Convert.ChangeType(value, underlyingType); 
     } 
     finally { } 
     return result; 
    } 
    public static bool AsBool(this string value) 
    { 
     return AsBool(value, false); 
    } 
    public static bool AsBool(this string value, bool fallbackValue) 
    { 
     if (String.IsNullOrEmpty(value)) 
      return fallbackValue; 
     switch (value.ToLower()) 
     { 
      case "1": 
      case "t": 
      case "true": 
       return true; 
      case "0": 
      case "f": 
      case "false": 
       return false; 
      default: 
       return fallbackValue; 
     } 
    } 

Respuesta

5

Puede echarlo a object y luego a T:

if (typeof(T) == typeof(bool)) 
{ 
    return (T)(object)AsBool(value, Convert.ToBoolean(fallbackValue)); 
} 
+3

parece mucho más limpio de esta manera :). ¿Cuál es la razón por la que no puedo lanzar directamente? – Silvermind

Cuestiones relacionadas