เมธอด SByte.CompareTo() ใน C# ใช้สำหรับเปรียบเทียบอินสแตนซ์ปัจจุบันกับออบเจ็กต์หรือค่า SByte ที่ระบุ และคืนค่าจำนวนเต็มที่บ่งชี้ความสัมพันธ์ระหว่างค่าทั้งสอง
ไวยากรณ์ (Syntax)
มีการโอเวอร์โหลด 2 รูปแบบ:
public int CompareTo (sbyte val); public int CompareTo (object ob);
val— ค่า SByte (จำนวนเต็ม 8 บิต เครื่องหมาย) ที่ต้องการเปรียบเทียบob— ออบเจ็กต์ที่ต้องการเปรียบเทียบ (ต้องเป็น SByte มิฉะนั้นจะโยนข้อยกเว้น)
ค่าที่คืน (Return Value)
| ค่า | ความหมาย |
|---|---|
| น้อยกว่า 0 | อินสแตนซ์ปัจจุบันน้อยกว่าค่าที่เปรียบเทียบ |
| เท่ากับ 0 | อินสแตนซ์ปัจจุบันเท่ากับค่าที่เปรียบเทียบ |
| มากกว่า 0 | อินสแตนซ์ปัจจุบันมากกว่าค่าที่เปรียบเทียบ |
ตัวอย่างที่ 1: เปรียบเทียบค่า SByte ทั้งคู่
using System;
public class Demo
{
public static void Main()
{
sbyte s1 = 55;
sbyte s2 = 55;
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");
}
}
ผลลัพธ์
Value of S1 = 55 Value of S2 = 55 s1 = s2
ตัวอย่างที่ 2: เปรียบเทียบ SByte กับออบเจ็กต์
using System;
public class Demo
{
public static void Main()
{
sbyte s1 = 55;
object s2 = (sbyte)55; // บอกซ์เป็น object
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");
}
}
ผลลัพธ์
Value of S1 = 55 Value of S2 = 55 s1 = s2
หมายเหตุสำคัญ
- หาก
obไม่ใช่ SByte จะเกิดArgumentException - เมธอดนี้ใช้งานได้กับค่าลบและบวกของ SByte (ช่วง -128 ถึง 127)
- เหมาะสำหรับการจัดเรียงหรือการตัดสินใจตามเงื่อนไขเชิงเปรียบเทียบ