2010-09-15 11 views
23

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

Welcher ist besser und warum?

+0

möglich duplicate von [.Net Parse versus Convert] (http://stackoverflow.com/questions/18465/net-parse-versus-convert) – JasonMArcher

Antwort

35

Sie sind genau die gleichen, außer dass Convert.ToInt32(null)0 zurückgibt.

Convert.ToInt32 ist wie folgt definiert:

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

Wo finden Sie ToInt32() Funktion Quellcode? Ich habe MSDN gegoogelt und kann die Details nicht finden, die du eingegeben hast. :-) –

+4

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

+2

Auch Reflektor ist eine Option: http://www.red-gate.com/ Produkte/Reflektor / –

5

Nun, Reflector sagt ...

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

So sind sie im Grunde das gleiche, außer dass Convert.ToInt32() hat eine zusätzliche Null-Check.

Verwandte Themen