VS 快捷鍵可以快速 override Equals 和 GetHashCode Method
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
在 class 上使用 Alt + Enter 就可以看見快捷功能,選擇 [產生 Equals 與 GetHashCode]勾選 [IEquatable<User>] 選項
產生完整的 User Class Code
public class User : IEquatable<User>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as User);
}
public bool Equals(User other)
{
return other != null &&
FirstName == other.FirstName &&
LastName == other.LastName;
}
public override int GetHashCode()
{
// VS 自動產生
int hashCode = 1938039292;
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(FirstName);
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(LastName);
return hashCode;
// 查資料時發現,下列寫法比較常見
return FirstName.GetHashCode() ^ LastName.GetHashCode();
}
}
Demo 範例
using System;
namespace IEquatableSample
{
class Program
{
static void Main(string[] args)
{
User UserA = new User
{
LastName = "姓",
FirstName = "名"
};
User UserB = new User
{
LastName = "姓",
FirstName = "名"
};
Console.WriteLine($"UserA == UserB:{UserA == UserB}");
Console.WriteLine($"UserA.Equals(UserB):{UserA.Equals(UserB)}");
}
}
}
結果
沒有留言:
張貼留言