使用对象作为通用字典键(Using the field of an object as a generic Dictionary key)

编程入门 行业动态 更新时间:2024-10-11 17:22:28
使用对象作为通用字典键(Using the field of an object as a generic Dictionary key)

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

说我有一个有属性的类:

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

我想创建一个:

Dictionary<Foo, List<Stuff>>

我想要具有相同FooID Foo对象被认为是同一个组。 我需要在Foo类中覆盖哪些方法?

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

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 }

And I want to create a:

Dictionary<Foo, List<Stuff>>

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?

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<Foo> ,但这是可选的:

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<T>来做同样的事情。

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

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

更多推荐

本文发布于:2023-07-27 15:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292371.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   对象   field   object   Dictionary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!