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

后端 未结 12 1644
星月不相逢
星月不相逢 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:45

    A string cannot be cast to an int through explicit casting. It must be converted using int.Parse.

    Convert.ToInt32 basically wraps this method:

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

提交回复
热议问题