HashSet.SetEquals 在两个相同的集合上 returns false

HashSet.SetEquals on two identical collections returns false

我有两个 HashSet<T> collections containing the same items (that is, different instances of the objects but with the same values). From my understanding of the SetEquals 方法下面的代码应该 return true 因为集合项 属性 值是相等的,但是它 returns false:

var source = new HashSet<AllocatedComponent>()
        {new AllocatedComponent() {
            Weighting = 100,
            ComponentId = 1, 
            Title = "Foo"}};
    
var destination = new HashSet<AllocatedComponent>()
        {new AllocatedComponent() {
            Weighting = 100,
            ComponentId = 1, 
            Title = "Foo"}};
    
Console.WriteLine(source.SetEquals(destination)); // False

任何人都可以解释一下我在这里做错了什么吗?我的目标是检查这两个集合是否包含相同数量的项目,以及相同的 属性 值。

我不太了解 Microsoft 文档的备注部分,因此可能忽略了一些非常明显的内容。

Net Fiddle here

从第一条评论开始让框架使用它们的数据比较对象,您必须重写 2 个方法 bool Equals(object o)int GetHashCode()。下面的代码给出了期望的结果(请注意,您必须为这两个实现使用所有数据成员)

using System;
using System.Collections.Generic;

public class AllocatedComponent
 
{
    public double Weighting { get; set; }
    public int ComponentId { get; set; }
    public string Title { get; set; }
    
    public override bool Equals(object o)
    {
        if(!(o is AllocatedComponent))
           return false;
        AllocatedComponent ac = (AllocatedComponent)o;
        return ac.Title == this.Title && ac.ComponentId == this.ComponentId && ac.Weighting == this.Weighting;
    }   
    public override int GetHashCode()
    {
        return this.Title.GetHashCode();
    }
}

public class Program
{
    public static void Main()
    {
        var source = new HashSet<AllocatedComponent>()
            {new AllocatedComponent() {
                Weighting = 100,
                ComponentId = 1, 
                Title = "Foo"}};
        
        var destination = new HashSet<AllocatedComponent>()
            {new AllocatedComponent() {
                Weighting = 100,
                ComponentId = 1, 
                Title = "Foo"}};
        
        Console.WriteLine(source.SetEquals(destination)); // False
    }
}