C# HashSet Generic allows duplicate

五迷三道 提交于 2019-12-08 03:26:06

问题


Reading HashSet on MSDN, it says with HashSet<T>, if T implements IEquatable<T> then the HashSet uses this for IEqualityComparer<T>.Default.

So, let the class Person:

public class Person : IEquality<Person>
{
    private string pName;
    public Person(string name){ pName=name; }
    public string Name
    {
        get { return pName; }
        set
        {
            if (pName.Equals(value, StringComparison.InvariantCultureIgnoreCase))
            {
              return;
            }
            pName = value;
        }
    }

    public bool Equals(Person other)
    {
        if(other==null){return false;}
        return pName.Equals(other.pName, StringComparison.InvariantCultureIgnoreCase);
    }

    public override bool Equals(object obj)
    {
        Person other = obj as Person;
        if(other==null){return false;}
        return Equals(other);
    }

    public override int GetHashCode(){return pName.GetHashCode();}

    public override string ToString(){return pName;}
}

So, let's define in another class or main function:

HashSet<Person> set = new HashSet<Person>();
set.Add(new Person("Smith"); // return true
Person p = new Person("Smi");
set.Add(p); // return true
p.Name = "Smith"; // no error occurs

And now, you've got 2 Person objects in the HashSet with the same name (so that, there are "Equals").

HashSet let us put duplicate objects.


回答1:


HashSet let us put duplicate objects.

It isn't letting you put in duplicate objects. The issue is that you're mutating the object after it's been added.

Mutating objects being used as keys in dictionaries or stored as hashes is always problematic, and something I would recommend avoiding.



来源:https://stackoverflow.com/questions/12751591/c-sharp-hashset-generic-allows-duplicate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!