Phương thức Int32.GetHashCode() trong C# được dùng để trả về mã băm (hash code) cho thể hiện hiện tại.
Cú pháp
Cú pháp như sau:
public override int GetHashCode();
Ví dụ 1 - Giá trị khác nhau
using System;
public class Demo
{
public static void Main()
{
int val1 = Int32.MinValue;
int val2 = 300;
Console.WriteLine("Value1 = " + val1);
Console.WriteLine("Value2 = " + val2);
Console.WriteLine("Are they equal? = " + val1.Equals(val2));
Console.WriteLine("HashCode for Value1 = " + val1.GetHashCode());
Console.WriteLine("HashCode for Value2 = " + val2.GetHashCode());
}
}
Kết quả
Value1 = -2147483648 Value2 = 300 Are they equal? = False HashCode for Value1 = -2147483648 HashCode for Value2 = 300
Ví dụ 2 - Giá trị bằng nhau
using System;
public class Demo
{
public static void Main()
{
int val1 = 50;
int val2 = 50;
Console.WriteLine("Value1 = " + val1);
Console.WriteLine("Value2 = " + val2);
Console.WriteLine("Are they equal? = " + val1.Equals(val2));
Console.WriteLine("HashCode for Value1 = " + val1.GetHashCode());
Console.WriteLine("HashCode for Value2 = " + val2.GetHashCode());
}
}
Kết quả
Value1 = 50 Value2 = 50 Are they equal? = True HashCode for Value1 = 50 HashCode for Value2 = 50