TryParse Typy dopuszczające wartości zerowe ogólnie [duplikat]
To pytanie ma już odpowiedź tutaj:
Przekształć ciąg na nullable type (int, double, etc ...) 16 odpowiedzi Generics i nullable type 7 odpowiedzi Napisałem przeciążony statycznyTryParse
metody dla następującychNullable
ypy int?
, short?
, long?
, double?
, DateTime?
, decimal?
, float?
, bool?
, byte?
ichar?
. Poniżej znajduje się niektóre z implementacji:
protected static bool TryParse(string input, out int? value)
{
int outValue;
bool result = Int32.TryParse(input, out outValue);
value = outValue;
return result;
}
protected static bool TryParse(string input, out short? value)
{
short outValue;
bool result = Int16.TryParse(input, out outValue);
value = outValue;
return result;
}
protected static bool TryParse(string input, out long? value)
{
long outValue;
bool result = Int64.TryParse(input, out outValue);
value = outValue;
return result;
}
Logika jest taka sama w każdej metodzie, z wyjątkiem tego, że używają różnych typów. Czy nie byłoby możliwe użycie ogólnych, aby nie musiałem mieć zbyt wiele zbędnego kodu? Podpis wyglądałby tak:
bool TryParse<T>(string input, out T value);
Dzięk