Is there a try Convert.ToInt32… avoiding exceptions

前端 未结 7 1873
长发绾君心
长发绾君心 2020-12-08 18:51

I\'d like to know if there is a \"safe\" way to convert an object to an int, avoiding exceptions.

I\'m looking for something like public static bo

7条回答
  •  一向
    一向 (楼主)
    2020-12-08 19:14

    No need to re-invent the wheel here. use int.TryParse to achieve your goal. It returns a bool to show that value is parsed or not. and if parsed the result is saved in the output variable.

    int result;
    object a = 5;
    if(int.TryParse(a.ToString(),out result))
    {
       Console.WriteLine("value is parsed");  //will print 5
    }    
    
    object b = a5;
    if(int.TryParse(b.ToString(),out result))
    {
        Console.WriteLine("value is parsed");  
    }
    else
    {
        Console.WriteLine("input is not a valid integer");  //will print this   
    }
    

提交回复
热议问题