C#HashSet Generic允许重复 [英] C# HashSet Generic allows duplicate

查看:143
本文介绍了C#HashSet Generic允许重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MSDN上读取HashSet,用HashSet<T>表示,如果T实现IEquatable<T>,则HashSet将其用于IEqualityComparer<T>.Default.

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

因此,让类Person:

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

现在,您在HashSet中有两个具有相同名称的Person对象(因此,有等于").

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

HashSet让我们放置重复的对象.

HashSet let us put duplicate objects.

推荐答案

HashSet让我们放置重复的对象.

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.

这篇关于C#HashSet Generic允许重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆