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

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

เมธอด Convert.ToUInt32() แปลงค่าที่ระบุเป็น uint (Unsigned 32-bit Integer) ช่วงค่า 0 ถึง 4,294,967,295

Overloads หลัก

  • ToUInt32(String) - จาก String
  • ToUInt32(Object) - จาก Object (IConvertible)
  • ToUInt32(String, IFormatProvider) - พร้อม Culture
  • และ Overloads สำหรับประเภทพื้นฐานอื่นๆ: bool, byte, char, DateTime, decimal, double, short, int, long, sbyte, float, ushort, ulong

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

using System;

public class Demo
{
    public static void Main()
    {
        string str = "210";
        uint res = Convert.ToUInt32(str);
        
        Console.WriteLine($"Converted string '{str}' to {res}");
    }
}

ผลลัพธ์

Converted string '210' to 210

ตัวอย่าง: แปลงจากประเภทอื่น

// จาก int (ต้องเป็นค่าบวก)
int signed = -10;
// uint unsigned = Convert.ToUInt32(signed); // OverflowException!

int positive = 100;
uint u1 = Convert.ToUInt32(positive); // 100

// จาก double
double d = 123.45;
uint u2 = Convert.ToUInt32(d); // 123 (Truncate ทศนิยม)

// จาก long
long big = 5_000_000_000;
uint u3 = Convert.ToUInt32(big); // OverflowException! > uint.MaxValue

// จาก object
object obj = "456";
uint u4 = Convert.ToUInt32(obj); // 456

ข้อยกเว้นที่อาจเกิด

  • OverflowException - ค่านอกช่วง uint (น้อยกว่า 0 หรือ มากกว่า uint.MaxValue)
  • FormatException - String รูปแบบไม่ถูกต้อง
  • InvalidCastException - Object ไม่ Implement IConvertible

ทางเลือกที่ปลอดภัยกว่า

// TryParse - ไม่โยน Exception
if (uint.TryParse(str, out uint result))
{
    Console.WriteLine($"Parsed: {result}");
}
else
{
    Console.WriteLine("Invalid format");
}

// Pattern Matching (C# 7+)
if (str is { } s && uint.TryParse(s, out var val))
{
    // use val
}

หมายเหตุ: uint ไม่ใช่ CLS-Compliant ควรใช้ int หรือ long สำหรับ Public API