Sto provando a convertire da String a un tipo generico. Il tipo generico sarà un Int32, Int64, Boolean, doppio e così via ... Ho provato due approcci:Convertitore di tipo generico - TypeConverter o Convert.ChangeType
public static Boolean TryParse<T>(String source, out T value) {
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
try {
value = (T)converter.ConvertFromString(source);
return true;
} catch {
value = default(T);
return false;
}
}
public static Boolean TryChangeType<T>(Object source, out T value) {
try {
Type type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
value = (T)Convert.ChangeType(source, type);
return true;
} catch {
value = default(T);
return false;
}
}
Il secondo è più generico come si accetta un oggetto.
Sto anche considerando di passare un IFormatProvider in TryChangeType che verrebbe utilizzato in Convert.ChangeType per risolvere i problemi di cultura e così via.
Considerate meglio il secondo approccio?
In qualsiasi modo posso migliorare il mio codice?
Possibile duplicato di [TypeConverter vs. Converti vs. TargetType.Parse] (http://stackoverflow.com/questions/7010669/typeconverter-vs-convert-vs-targettype-parse) –