如果我想使用对象作为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.
更多推荐
发布评论