2012-08-24 16 views
6

Mam następujące rozszerzenia metody na ciągi, aby móc to zrobić ("true").As<bool>(false) Specjalnie dla booleans będzie używał AsBool() do niestandardowej konwersji. Jakoś nie mogę rzucić z T na Bool i odwrotnie. Zrobiłem to działając przy użyciu następującego kodu, jednak wydaje się to trochę przesadzone.Przesyłaj T do bool i vice versa

Chodzi o tej linii:
(T)Convert.ChangeType(AsBool(value, Convert.ToBoolean(fallbackValue)), typeof(T))
wolałbym użyć następujących, ale nie będzie skompilować:
(T)AsBool(value, (bool)fallbackValue), typeof(T))

Am I czegoś brakuje lub jest to najkrótsza droga ?

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

Odpowiedz

5

można miotać object a następnie T:

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

wygląda o wiele czystsze ten sposób :). Z jakiego powodu nie mogę bezpośrednio rzucać? – Silvermind

Powiązane problemy