What is the difference between Convert.ToInt32 and (int)?

后端 未结 12 1594
星月不相逢
星月不相逢 2020-11-27 03:11

The following code throws an compile-time error like

Cannot convert type \'string\' to \'int\'

string name = Session[\"name1\"].ToString();
int i = (         


        
12条回答
  •  抹茶落季
    2020-11-27 03:51

    (int)foo is simply a cast to the Int32 (int in C#) type. This is built into the CLR and requires that foo be a numeric variable (e.g. float, long, etc.) In this sense, it is very similar to a cast in C.

    Convert.ToInt32 is designed to be a general conversion function. It does a good deal more than casting; namely, it can convert from any primitive type to a int (most notably, parsing a string). You can see the full list of overloads for this method here on MSDN.

    And as Stefan Steiger mentions in a comment:

    Also, note that on a numerical level, (int) foo truncates foo (ifoo = Math.Floor(foo)), while Convert.ToInt32(foo) uses half to even rounding (rounds x.5 to the nearest EVEN integer, meaning ifoo = Math.Round(foo)). The result is thus not just implementation-wise, but also numerically not the same.

提交回复
热议问题