2012-08-24 9 views
6

I seguenti metodi di estensione per le stringhe sono in grado di eseguire questa operazione ("true").As<bool>(false) In particolare per i booleani verrà utilizzato lo AsBool() per eseguire alcune conversioni personalizzate. In qualche modo non posso lanciare da T a Bool e viceversa. L'ho fatto funzionare usando il seguente codice, ma sembra un po 'eccessivo.Fusione T per bool e viceversa

E 'su questa linea:
(T)Convert.ChangeType(AsBool(value, Convert.ToBoolean(fallbackValue)), typeof(T))
Avrei preferito usare i seguenti, ma non si compila:
(T)AsBool(value, (bool)fallbackValue), typeof(T))

mi sto perdendo qualcosa o è questa la via più breve per andare ?

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; 
     } 
    } 

risposta

5

È possibile gettarlo ai object e poi a T:

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

sembra molto più pulito in questo modo :). Qual è la ragione per cui non posso trasmettere direttamente? – Silvermind

Problemi correlati