Int32.TryParse() returns zero on failure - success or failure?

后端 未结 5 1604
萌比男神i
萌比男神i 2021-01-01 09:06

I read this from msdn about Int32.TryParse()

When this method returns, contains the 32-bit signed integer value equivalent to the num

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 09:21

    The Int32.TryParse() method returns a boolean value as return and provides the converted value as an out parameter. So you can check for the return boolean value for the status.

    private static void TryToParse(string value)
       {
          int number;
          bool result = Int32.TryParse(value, out number);
          if (result)
          {
             Console.WriteLine("Converted '{0}' to {1}.", value, number);         
          }
          else
          {
             if (value == null) value = ""; 
             Console.WriteLine("Attempted conversion of '{0}' failed.", value);
          }
       }
    

提交回复
热议问题