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

เมธอด SByte.GetHashCode() ใน C# พร้อมตัวอย่าง


เมธอด SByte.GetHashCode() ใน C# ใช้สำหรับคืนค่ารหัสแฮช (hash code) ของอินสแตนซ์ SByte (จำนวนเต็ม 8 บิต เครื่องหมาย) นี้

ไวยากรณ์ (Syntax)

public override int GetHashCode ();

ตัวอย่างที่ 1: HashCode ของค่า SByte ต่างกัน

using System;

public class Demo
{
    public static void Main()
    {
        sbyte s1 = 50;
        sbyte s2 = 75;

        Console.WriteLine("Value of S1 = " + s1);
        Console.WriteLine("Value of S2 = " + s2);
        Console.WriteLine("Is s1 and s2 equal? = " + s1.Equals(s2));
        Console.WriteLine("HashCode for s1 = " + s1.GetHashCode());
        Console.WriteLine("HashCode for s2 = " + s2.GetHashCode());  // ตัวอย่างเดิมมีบั๊กใช้ s1.GetHashCode() ซ้ำ
    }
}

ผลลัพธ์

Value of S1 = 50
Value of S2 = 75
Is s1 and s2 equal? = False
HashCode for s1 = 50
HashCode for s2 = 75

ตัวอย่างที่ 2: เปรียบเทียบ SByte กับ Object

using System;

public class Demo
{
    public static void Main()
    {
        sbyte s1 = 55;
        object s2 = (sbyte)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");

        Console.WriteLine("HashCode for s1 = " + s1.GetHashCode());
        Console.WriteLine("HashCode for s2 = " + ((sbyte)s2).GetHashCode());
    }
}

ผลลัพธ์

Value of S1 = 55
Value of S2 = 55
s1 = s2
HashCode for s1 = 55
HashCode for s2 = 55

ข้อสังเกตและแก้ไขจากตัวอย่างต้นฉบับ

  • ในตัวอย่างแรก โค้ดต้นฉบับพิมพ์ s1.GetHashCode() สำหรับ s2 ทั้งสองครั้ง — ได้แก้ไขเป็น s2.GetHashCode() แล้ว
  • ตัวอย่างที่สองของต้นฉบับมีค่า Output ไม่สอดคล้องกับโค้ด (แสดงค่า 10 และ 100) — ได้ปรับแก้ให้สอดคล้องกัน
  • สำหรับ SByte ค่า HashCode จะเท่ากับค่าตัวเลขนั้นๆ เนื่องจากช่วงค่าเล็ก (-128 ถึง 127)
  • เมื่อบอกซ์ (box) เป็น object ต้องแคสต์กลับเป็น sbyte ก่อนเรียก GetHashCode()