2010-09-15 17 views
23

intID1 = Int32.Parse (myValue.ToString()); intID2 = Convert.ToInt32 (myValue);Int32.Parse() VS Convert.ToInt32()?

¿Cuál es mejor y por qué?

+0

posible duplicado de [.Net Parse versus Convert] (http://stackoverflow.com/questions/18465/net-parse-versus-convert) – JasonMArcher

Respuesta

35

Son exactamente lo mismo, excepto que Convert.ToInt32(null) devuelve 0.

Convert.ToInt32 se define de la siguiente manera:

public static int ToInt32(String value) { 
     if (value == null) 
      return 0; 
     return Int32.Parse(value, CultureInfo.CurrentCulture); 
    } 
+0

¿Dónde se encuentra el código fuente de la función ToInt32()? Busqué en Google MSDN y no puedo encontrar los detalles como los ingresó. :-) –

+4

@Nano: http://referencesource.microsoft.com/ o http://en.wikipedia.org/wiki/Shared_Source_Common_Language_Infrastructure – SLaks

+2

También Reflector es una opción: http://www.red-gate.com/ productos/reflector / –

5

Bueno, dice reflector ...

public static int ToInt32(string value) 
{ 
    if (value == null) 
    { 
     return 0; 
    } 
    return int.Parse(value, CultureInfo.CurrentCulture); 
} 

public static int Parse(string s) 
{ 
    return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); 
} 

por lo que son básicamente el mismo, excepto que Convert.ToInt32() hace una comprobación nula añadido.