我嘗試使用. HashSet我有以下代碼:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> A = new HashSet<int>() { 1, 2 };
HashSet<int> B = new HashSet<int>() { 1, 2 };
HashSet<HashSet<int>> SET = new HashSet<HashSet<int>>() { A, B };
// Desired: 1 (A and B are expected being equal)
// Actual: 2
Console.WriteLine(SET.Count);
Console.ReadKey();
}
}
似乎HashSet相等是不合適的,因為A并且B必須被認為是相同的,但是對于 HashSet 它們是不同的物件。如何重新定義 HashSet 的相等性?
uj5u.com熱心網友回復:
您應該解釋.Net如何在以下幫助下比較您的自定義資料(HashSet<T>在您的情況下)IEqualityComparer<T>:
public sealed class HashSetComparer<T> : IEqualityComparer<HashSet<T>> {
public bool Equals(HashSet<T>? left, HashSet<T>? right) {
if (ReferenceEquals(left, right))
return true;
if (left == null || right == null)
return false;
return left.SetEquals(right);
}
public int GetHashCode(HashSet<T> item) {
//TODO: improve; simplest, but not that good implementation
return item == null ? -1 : item.Count;
}
}
然后在創建時提及比較規則SET:
...
HashSet<HashSet<int>> SET = new HashSet<HashSet<int>>(new HashSetComparer<int>()) {
A, B
};
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451718.html
上一篇:計算笛卡爾空間中的偏移坐標
