Qual è il modo migliore per eseguire l'equivalente di int.TryParse (che si trova in .net 2.0 in poi) utilizzando .net 1.1.Qual è l'alternativa migliore a int.TryParse per .net 1.1
7
A
risposta
11
Ovviamente,
class Int32Util
{
public static bool TryParse(string value, out int result)
{
result = 0;
try
{
result = Int32.Parse(value);
return true;
}
catch(FormatException)
{
return false;
}
catch(OverflowException)
{
return false;
}
}
}
2
try
{
var i = int.Parse(value);
}
catch(FormatException ex)
{
Console.WriteLine("Invalid format.");
}
+1
Fa non il lancio eccezione/gestione creare un bel po 'di overhead però? –
1
Koistya quasi aveva. Nessun comando var in .NET 1.1.
Se posso essere così audace:
try
{
int i = int.Parse(value);
}
catch(FormatException ex)
{
Console.WriteLine("Invalid format.");
}
1
C'è una TryParse per il doppio, quindi se si utilizza questo, scegliere l'opzione "NumberStyles.Integer" e verificare che il doppio risultante è entro i confini del Int32, è possibile determinare se la stringa è un intero senza generare un'eccezione.
speranza che questo aiuti, Jamie
private bool TryIntParse(string txt)
{
try
{
double dblOut = 0;
if (double.TryParse(txt, System.Globalization.NumberStyles.Integer
, System.Globalization.CultureInfo.CurrentCulture, out dblOut))
{
// determined its an int, now check if its within the Int32 max min
return dblOut > Int32.MinValue && dblOut < Int32.MaxValue;
}
else
{
return false;
}
}
catch(Exception ex)
{
throw ex;
}
}
Potrebbe voler "restituire True" da qualche parte in questo? – Pondidum
@Pondidum: buona chiamata! Grazie. –