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

การแปลงสตริงเป็น long ใน C# ด้วย long.Parse()

เมธอด long.Parse() ใช้แปลงสตริงที่เป็นตัวเลขให้กลายเป็นชนิดข้อมูล long (Int64) ซึ่งรองรับค่าตั้งแต่ -9,223,372,036,854,775,808 ถึง 9,223,372,036,854,775,807

รูปแบบการใช้งาน

string str = "6987646475767";
long number = long.Parse(str);

โค้ดตัวอย่างสมบูรณ์

using System;

class Demo
{
    static void Main()
    {
        string str = "6987646475767";
        
        try
        {
            long result = long.Parse(str);
            Console.WriteLine($"สตริงต้นฉบับ: {str}");
            Console.WriteLine($"ค่า long: {result}");
            Console.WriteLine($"ชนิดข้อมูล: {result.GetType()}");
        }
        catch (FormatException)
        {
            Console.WriteLine("รูปแบบสตริงไม่ถูกต้อง (ไม่ใช่ตัวเลข)");
        }
        catch (OverflowException)
        {
            Console.WriteLine("ค่ามากเกินกว่าที่ long จะเก็บได้");
        }
        
        // ตัวอย่างเพิ่มเติม
        Console.WriteLine("\n--- ตัวอย่างเพิ่มเติม ---");
        string[] testValues = { "123", "-456", "0", "9223372036854775807", "9223372036854775808" };
        
        foreach (var s in testValues)
        {
            try
            {
                long val = long.Parse(s);
                Console.WriteLine($"  '{s}' → {val} ✓");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  '{s}' → ERROR: {ex.GetType().Name}");
            }
        }
    }
}

ผลลัพธ์

สตริงต้นฉบับ: 6987646475767
ค่า long: 6987646475767
ชนิดข้อมูล: System.Int64

--- ตัวอย่างเพิ่มเติม ---
  '123' → 123 ✓
  '-456' → -456 ✓
  '0' → 0 ✓
  '9223372036854775807' → 9223372036854775807 ✓ (MaxValue)
  '9223372036854775808' → ERROR: OverflowException

เมธอดแปลงที่เกี่ยวข้อง

เมธอดคำอธิบายกรณีผิดพลาด
long.Parse()แปลงสตริงเป็น longโยน Exception
long.TryParse()พยายามแปลง คืน boolไม่โยน Exception, คืน false
Convert.ToInt64()แปลงจาก object ใดๆโยน Exception (null คืน 0)

แนะนำ: ใช้ TryParse เพื่อความปลอดภัย

string input = Console.ReadLine();

if (long.TryParse(input, out long number))
{
    Console.WriteLine($"แปลงสำเร็จ: {number}");
}
else
{
    Console.WriteLine("กรุณาป้อนตัวเลขที่ถูกต้อง");
}

รูปแบบตัวเลขที่รองรับ

  • ตัวเลขจำนวนเต็มบวก/ลบ: "123", "-456"
  • ตัวเลขพร้อมเครื่องหมายบวก: "+789"
  • ตัวเลขพร้อมคั่นหลักพัน (ต้องใช้ NumberStyles): "1,234,567"
  • เลขฐานสิบหก (Hexadecimal): long.Parse("FF", NumberStyles.HexNumber) = 255

ข้อควรระวัง

  • สตริงว่างหรือ null จะโยน ArgumentNullException หรือ FormatException
  • ช่องว่างนำหน้า/ท้าย สตริงจะถูกยอมรับ (trim อัตโนมัติ)
  • ไม่รองรับตัวเลขทศนิยม (ใช้ double.Parse แทน)