使用一个对象作为一个通用的字典关键 [英] Using an object as a generic Dictionary key

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

问题描述

如果我想使用对象作为密钥的词典,我需要重写,使他们在一个特定的方式来比较有什么方法呢?

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>>

我想对象具有相同 FooID 被认为是同一组。我需要在类重写哪些方法?

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?

要总结一下:我想分类的东西对象到列表中,由对象分组。 的东西的对象将有一个 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.

推荐答案

在默认情况下,这两种重要的方法是 GetHash code()等于()。重要的是,如果两件事情是相等的(等于()返回true),它们具有相同的散列code。例如,你可能回归FooID;作为 GetHash code()如果你想,随着比赛。你也可以实施 IEquatable&LT;富&GT; ,但这是可选的:

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&LT; T&GT; 做同样的

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

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