📜  C#中的Int32.Parse(String)方法与示例

📅  最后修改于: 2021-05-29 18:52:36             🧑  作者: Mango

Int32.Parse(String)方法用于将数字的字符串表示形式转换为其等效的32位有符号整数。

句法:

public static int Parse (string str);

在这里, str是一个包含要转换的数字的字符串。 str的格式为[可选空白] [可选符号] digits [可选空白]

返回值:这是一个32位带符号整数,等效于str中包含的数字。

例外情况:

  • ArgumentNullException :如果str为null。
  • FormatException :如果str的格式不正确。
  • OverflowException :如果str表示一个小于MinValue或大于MaxValue的数字

下面的程序说明了上面讨论的方法的使用:

范例1:

// C# program to demonstrate
// Int32.Parse(String) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // passing different values
        // to the method to check
        checkParse("2147483647");
        checkParse("214,7483,647");
        checkParse("-2147483");
        checkParse(" 2183647 ");
    }
  
    // Defining checkParse method
    public static void checkParse(string input)
    {
  
        try {
  
            // declaring Int32 variable
            int val;
  
            // getting parsed value
            val = Int32.Parse(input);
            Console.WriteLine("'{0}' parsed as {1}", input, val);
        }
  
        catch (FormatException) {
            Console.WriteLine("Can't Parsed '{0}'", input);
        }
    }
}
输出:
'2147483647' parsed as 2147483647
Can't Parsed '214,7483,647'
'-2147483' parsed as -2147483
' 2183647 ' parsed as 2183647

示例2:对于ArgumentNullException

// C# program to demonstrate
// Int32.Parse(String) Method
// for ArgumentNullException
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        try {
  
            // passing null value as a input
            checkParse(null);
        }
        catch (ArgumentNullException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
        catch (FormatException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining checkparse method
    public static void checkParse(string input)
    {
  
        // declaring Int32 variable
        int val;
  
        // getting parsed value
        val = Int32.Parse(input);
        Console.WriteLine("'{0}' parsed as {1}", input, val);
    }
}
输出:
Exception Thrown: System.ArgumentNullException

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.int32.parse?view=netframework-4.7.2#System_Int32_Parse_System_String_