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

เมธอด UInt16.ToString ใน C# พร้อมตัวอย่าง


บทนำ

เมธอด UInt16.ToString() ใน C# ใช้แปลงค่าตัวเลขของอินสแตนซ์ UInt16 ปัจจุบันให้เป็นการแทนค่าในรูปแบบสตริง ซึ่งเป็นจำนวนเต็ม 16 บิตที่ไม่มีเครื่องหมาย (unsigned short)

ไวยากรณ์ (Syntax)

public override string ToString();

ตัวอย่างที่ 1: การแปลงค่า UInt16 ทั่วไป

using System;

public class Demo 
{
    public static void Main()
    {
        ushort val1 = 100;
        ushort val2 = 80;
        
        Console.WriteLine("Value1 (String representation) = " + val1.ToString());
        Console.WriteLine("Value2 (String representation) = " + val2.ToString());
        
        bool res = val1.Equals(val2);
        Console.WriteLine("Return value (comparison) = " + res);
        
        if (res)
            Console.WriteLine("val1 = val2");
        else
            Console.WriteLine("val1 != val2");
    }
}

ผลลัพธ์

Value1 (String representation) = 100
Value2 (String representation) = 80
Return value (comparison) = False
val1 != val2

ตัวอย่างที่ 2: ค่าต่ำสุดและค่าสูงสุดของ UInt16

using System;

public class Demo 
{
    public static void Main()
    {
        ushort val1 = 0;
        ushort val2 = UInt16.MaxValue;
        
        Console.WriteLine("Value1 (String representation) = " + val1.ToString());
        Console.WriteLine("Value2 (String representation) = " + val2.ToString());
        
        bool res = val1.Equals(val2);
        Console.WriteLine("Return value (comparison) = " + res);
        
        if (res)
            Console.WriteLine("val1 = val2");
        else
            Console.WriteLine("val1 != val2");
    }
}

ผลลัพธ์

Value1 (String representation) = 0
Value2 (String representation) = 65535
Return value (comparison) = False
val1 != val2

สรุป

เมธอด ToString() ของ UInt16 ให้การแปลงเป็นสตริงแบบมาตรฐาน สามารถใช้ overload ที่รับ format string เช่น "X" สำหรับฐานสิบหก "D5" สำหรับจำนวนหลักคงที่ และ IFormatProvider สำหรับการจัดรูปแบบตามวัฒนธรรม (culture-specific formatting)