เมธอด SByte.ToString() ใน C# ใช้แปลงค่าตัวเลขของ instance นี้ให้เป็นการแสดงผลสตริงที่เทียบเท่า SByte (signed byte) เป็นจำนวนเต็ม 8-bit ที่มีเครื่องหมาย ช่วงค่า -128 ถึง 127
รูปแบบไวยากรณ์ (Syntax)
public override string ToString();
ตัวอย่างที่ 1: การแปลงพื้นฐานพร้อม CompareTo และ GetHashCode
using System;
public class Demo
{
public static void Main()
{
sbyte s1 = 10;
sbyte s2 = 100;
Console.WriteLine("Value of S1 = " + s1);
Console.WriteLine("Value of S2 = " + s2);
int res = s1.CompareTo(s2);
if (res > 0)
Console.WriteLine("s1 > s2");
else if (res < 0)
Console.WriteLine("s1 < s2");
else
Console.WriteLine("s1 = s2");
Console.WriteLine("\nHashCode for s1 = " + s1.GetHashCode());
Console.WriteLine("GetTypeCode for s1 = " + s1.GetTypeCode());
Console.WriteLine("String representation for s1 = " + s1.ToString());
Console.WriteLine("\nHashCode for s2 = " + s2.GetHashCode());
Console.WriteLine("GetTypeCode for s2 = " + s2.GetTypeCode());
Console.WriteLine("String representation for s2 = " + s2.ToString());
}
}
ผลลัพธ์
Value of S1 = 10 Value of S2 = 100 s1 < s2 HashCode for s1 = 10 HashCode for s2 = 100 GetTypeCode for s1 = SByte String representation for s1 = 10 GetTypeCode for s2 = SByte String representation for s2 = 100
ตัวอย่างที่ 2: เปรียบเทียบกับ SByte.MaxValue
using System;
public class Demo
{
public static void Main()
{
sbyte s1 = 99;
sbyte s2 = SByte.MaxValue; // 127
Console.WriteLine("Value of S1 = " + s1);
Console.WriteLine("Value of S2 = " + s2);
Console.WriteLine("Is s1 and s2 equal? = " + s1.Equals(s2));
int res = s1.CompareTo(s2);
if (res > 0)
Console.WriteLine("s1 > s2");
else if (res < 0)
Console.WriteLine("s1 < s2");
else
Console.WriteLine("s1 = s2");
Console.WriteLine("String representation for s1 = " + s1.ToString());
Console.WriteLine("String representation for s2 = " + s2.ToString());
}
}
ผลลัพธ์
Value of S1 = 99 Value of S2 = 127 Is s1 and s2 equal? = False s1 < s2 String representation for s1 = 99 String representation for s2 = 127
สรุปและข้อมูลเพิ่มเติม
SByte= signed 8-bit integer (-128 ถึง 127)Byte= unsigned 8-bit integer (0 ถึง 255) - ใช้บ่อยกว่าToString()แปลงเป็นสตริงทศนิยมปกติ (ไม่มี format overload เหมือน Int32/Int64)GetHashCode()คืนค่าเท่ากับค่าตัวเลขเอง (สำหรับค่าที่เล็ก)GetTypeCode()คืนค่าTypeCode.SByte- ใช้ SByte เมื่อต้องการ byte ที่มีเครื่องหมาย (เช่น offset, delta, signed data)