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

📅  最后修改于: 2021-05-29 19:26:53             🧑  作者: Mango

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

句法:

public static ulong Parse (string str);

在这里, str是一个包含要转换的数字的字符串。 str的格式为[可选空白] [可选符号] digits [可选空白] 。该符号可以是正号或负号。但是负号只能与零一起使用,否则它将抛出OverflowException

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

例外情况:

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

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

范例1:

// C# program to demonstrate
// UInt64.Parse(String) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // passing different values
        // to the method to check
        checkParse("18446744073709551615");
        checkParse("454654615,784");
        checkParse("-564564564");
        checkParse(" 119846456456  ");
    }
  
    // Defining checkParse method
    public static void checkParse(string input)
    {
  
        try {
  
            // declaring UInt64 variable
            ulong val;
  
            // getting parsed value
            val = UInt64.Parse(input);
            Console.WriteLine("'{0}' parsed as {1}", input, val);
        }
  
        catch (OverflowException) {
  
            Console.WriteLine("Can't Parsed '{0}'", input);
        }
  
        catch (FormatException) {
  
            Console.WriteLine("Can't Parsed '{0}'", input);
        }
    }
}
输出:
'18446744073709551615' parsed as 18446744073709551615
Can't Parsed '454654615,784'
Can't Parsed '-564564564'
' 119846456456  ' parsed as 119846456456

示例2:对于ArgumentNullException

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

参考:

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