使用对象的字段作为通用字典键 [英] Using the field of an object as a generic Dictionary key

查看:31
本文介绍了使用对象的字段作为通用字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想使用对象作为 Dictionary 的键,我需要重写哪些方法以使它们以特定方式进行比较?

If I want to use objects as the keys for a Dictionary, what methods will I need to override to make them compare in a specific way?

假设我有一个具有属性的类:

Say I have a a class which has properties:

class Foo {
    public string Name { get; set; }
    public int FooID { get; set; }

    // elided
} 

我想创建一个:

Dictionary<Foo, List<Stuff>>

我希望具有相同 FooIDFoo 对象被视为同一组.我需要在 Foo 类中覆盖哪些方法?

I want Foo objects with the same FooID to be considered the same group. Which methods will I need to override in the Foo class?

总结:我想将 Stuff 对象分类到列表中,按 Foo 对象分组.Stuff 对象将有一个 FooID 将它们链接到它们的类别.

To summarize: I want to categorize Stuff objects into lists, grouped by Foo objects. Stuff objects will have a FooID to link them to their category.

推荐答案

默认情况下,两个重要的方法是 GetHashCode()Equals().重要的是,如果两件事相等(Equals() 返回 true),则它们具有相同的哈希码.例如,您可能会返回 FooID;"作为 GetHashCode() 如果你想要它作为匹配.你也可以实现 IEquatable,但这是可选的:

By default, the two important methods are GetHashCode() and Equals(). It is important that if two things are equal (Equals() returns true), that they have the same hash-code. For example, you might "return FooID;" as the GetHashCode() if you want that as the match. You can also implement IEquatable<Foo>, but that is optional:

class Foo : IEquatable<Foo> {
    public string Name { get; set;}
    public int FooID {get; set;}

    public override int GetHashCode() {
        return FooID;
    }
    public override bool Equals(object obj) {
        return Equals(obj as Foo);
    }
    public bool Equals(Foo obj) {
        return obj != null && obj.FooID == this.FooID;
    }
}

最后,另一种选择是提供一个 IEqualityComparer 来做同样的事情.

Finally, another alternative is to provide an IEqualityComparer<T> to do the same.

这篇关于使用对象的字段作为通用字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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