Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Convert.ToUInt64 Method ใน C#: แปลงเป็น Unsigned 64-bit Integer

เมธอด Convert.ToUInt64() แปลงค่าที่ระบุเป็น ulong (Unsigned 64-bit Integer) ช่วงค่า 0 ถึง 18,446,744,073,709,551,615

ตัวอย่าง: แปลงจาก Char

using System;

public class Demo
{
    public static void Main()
    {
        char ch = 'a';
        ulong res = Convert.ToUInt64(ch);
        
        Console.WriteLine($"Converted char '{ch}' to {res}");
    }
}

ผลลัพธ์

Converted char 'a' to 97

Overloads และตัวอย่างเพิ่มเติม

// จาก String
ulong u1 = Convert.ToUInt64("18446744073709551615"); // Max Value

// จาก int (ต้องเป็นบวก)
ulong u2 = Convert.ToUInt64(42); // 42

// จาก long (ต้องเป็นบวก)
ulong u3 = Convert.ToUInt64(10000000000L); // 10B

// จาก double
ulong u4 = Convert.ToUInt64(123.9); // 123 (Truncate)

// จาก byte[]
byte[] bytes = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
ulong u5 = BitConverter.ToUInt64(bytes, 0); // 使用 BitConverter

// จาก object
object obj = "999";
ulong u6 = Convert.ToUInt64(obj); // 999

ข้อยกเว้น

  • OverflowException - ค่านอกช่วง ulong (ติดลบ หรือ > ulong.MaxValue)
  • FormatException - String Format ผิด
  • InvalidCastException - Object ไม่ Convertible

การแปลงปลอดภัย (TryParse)

string input = "12345";
if (ulong.TryParse(input, out ulong value))
{
    Console.WriteLine($"Success: {value}");
}
else
{
    Console.WriteLine("Invalid ulong format");
}

หมายเหตุ: ulong ไม่ใช่ CLS-Compliant ใช้ long หรือ decimal สำหรับ Public API แทน