2010-09-15 65 views

回答

35

它們完全一樣,只是Convert.ToInt32(null)返回0

Convert.ToInt32定義如下:

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

你在哪裏找到ToInt32()函數的源代碼?我GOOGLE了MSDN,無法找到像你輸入的細節。 :-) – 2010-09-15 01:07:08

+4

@Nano:http://referencesource.microsoft.com/或http://en.wikipedia.org/wiki/Shared_Source_Common_Language_Infrastructure – SLaks 2010-09-15 01:08:56

+2

另外Reflector是一個選項:http://www.red-gate.com/產品/反射/ – 2010-09-15 01:22:32

5

好,反射說...

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

所以他們基本上只是Convert.ToInt32()同樣不增加的空檢查。