【发布时间】:2015-08-03 15:08:56
【问题描述】:
我有以下从 Tuple 派生的自定义类:
public class CustomTuple : Tuple<List<string>, DateTime?>
{
public CustomTuple(IEnumerable<string> strings, DateTime? time)
: base(strings.OrderBy(x => x).ToList(), time)
{
}
}
和HashSet<CustomTuple>。问题是当我将项目添加到集合时,它们不会被识别为重复项。即这输出2,但它应该输出1:
void Main()
{
HashSet<CustomTuple> set = new HashSet<CustomTuple>();
var a = new CustomTuple(new List<string>(), new DateTime?());
var b = new CustomTuple(new List<string>(), new DateTime?());
set.Add(a);
set.Add(b);
Console.Write(set.Count); // Outputs 2
}
如何覆盖 Equals 和 GetHashCode 方法以使此代码输出一组计数 1?
【问题讨论】:
-
您覆盖它们,以便当它们应该相等时,该方法返回 true。
-
我知道 - 但我尝试的方法不起作用。
-
你认为什么是平等的?列表中的所有字符串都匹配并且日期匹配?所以在你的
equals方法中这样做。 (我会先检查日期以提高效率)。 -
是的,我认为这是平等的。
-
那么你的代码呢?请注意,
GetHashCode的结果必须在Equals被调用之前匹配。
标签: c# tuples equals hashset gethashcode