Int32.Parse () VS Convert.ToInt32 ()?


IntID1 = Int32.Parse (MyValue.toString()); intID2 = Convertir.ToInt32 (MyValue);

¿Cuál es mejor y por qué?

 23
Author: Nano HE, 2010-09-15

2 answers

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

Convert.ToInt32 se define como sigue:

    public static int ToInt32(String value) {
        if (value == null) 
            return 0;
        return Int32.Parse(value, CultureInfo.CurrentCulture);
    }
 35
Author: SLaks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-15 00:59:40

Bueno, el Reflector dice...

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

Así que son básicamente lo mismo excepto que Convert.ToInt32() hace una comprobación null añadida.

 5
Author: Adam P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-15 07:54:29