2009-04-02 3 views

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

Potrebbe voler "restituire True" da qualche parte in questo? – Pondidum

+0

@Pondidum: buona chiamata! Grazie. –

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