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

📅  最后修改于: 2023-12-03 15:14:31.741000             🧑  作者: Mango

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

在C#中,Int64.Parse(String)方法可以将字符串转换为64位有符号整数类型。该方法接收一个字符串参数,并返回相应的64位整数值。

下面是该方法的语法:

public static long Parse(string s)

其中,s参数是要转换成64位整数的字符串表示。如果s参数不能转换为64位整数,该方法将抛出一个异常。

下面是使用Int64.Parse方法将字符串转换为64位整数的示例:

string input1 = "1234567890123456789"; // 要转换的字符串
long number1;

try
{
    // 将字符串转换为64位整数
    number1 = Int64.Parse(input1);
    Console.WriteLine(number1); // 输出:1234567890123456789
}
catch (FormatException)
{
    Console.WriteLine($"Unable to parse '{input1}'");
}

string input2 = "This is not a number"; // 要转换的字符串
long number2;

try
{
    // 将字符串转换为64位整数
    number2 = Int64.Parse(input2);
    Console.WriteLine(number2);
}
catch (FormatException)
{
    Console.WriteLine($"Unable to parse '{input2}'"); // 输出:Unable to parse 'This is not a number'
}

在上面的示例中,我们使用Int64.Parse方法将两个字符串转换为64位整数类型。第一个字符串可以成功转换为整数,而第二个字符串不能转换为整数,因此Int64.Parse方法抛出一个FormatException异常。

需要注意的是,Int64.Parse方法只能将表示64位整数的字符串转换为64位整数类型。如果字符串表示不正确,该方法将抛出一个FormatException异常。如果字符串表示的值超出了64位整数类型的取值范围,该方法将抛出一个OverflowException异常。因此,在使用Int64.Parse方法时,务必注意输入参数的合法性。