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

📅  最后修改于: 2021-05-29 14:30:49             🧑  作者: Mango

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

句法:

public static long Parse (string str);

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

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

例外情况:

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

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

范例1:

// C# program to demonstrate
// Int64.Parse(String) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // passing different values
        // to the method to check
        checkParse("9223372036854775807");
        checkParse("29,22337,20368547");
        checkParse("-922337203685477");
        checkParse(" 9223372075807");
    }
  
    // Defining checkParse method
    public static void checkParse(string input)
    {
  
        try {
  
            // declaring Int64 variable
            long val;
  
            // getting parsed value
            val = Int64.Parse(input);
            Console.WriteLine("'{0}' parsed as {1}", input, val);
        }
  
        catch (FormatException) 
        {
            Console.WriteLine("Can't Parsed '{0}'", input);
        }
    }
}
输出:
'9223372036854775807' parsed as 9223372036854775807
Can't Parsed '29,22337,20368547'
'-922337203685477' parsed as -922337203685477
' 9223372075807' parsed as 9223372075807

示例2:对于ArgumentNullException

// C# program to demonstrate
// Int64.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 Int64 variable
        long val;
  
        // getting parsed value
        val = Int64.Parse(input);
        Console.WriteLine("'{0}' parsed as {1}", input, val);
    }
}
输出:
Exception Thrown: System.ArgumentNullException

参考:

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