What's the main difference between int.Parse() and Convert.ToInt32

前端 未结 13 2288
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:47
  • What is the main difference between int.Parse() and Convert.ToInt32()?
  • Which one is to be preferred
13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 08:56

    It depends on the parameter type. For example, I just discovered today that it will convert a char directly to int using its ASCII value. Not exactly the functionality I intended...

    YOU HAVE BEEN WARNED!

    public static int ToInt32(char value)
    {
        return (int)value;
    } 
    
    Convert.ToInt32('1'); // Returns 49
    int.Parse('1'); // Returns 1
    

提交回复
热议问题