将对象的字段用作通用字典键 [英] Using the field of an object as a generic Dictionary key
问题描述
如果我想使用对象作为 Dictionary 的关键字,我需要重写哪些方法才能以特定方式进行比较?
假设我有一个有属性的类:
$ p $ class Foo {
公共字符串名称{get;组; }
public int FooID {get;组; }
//已删除
}
我想创建一个:
Dictionary< Foo,List< Stuff>>
我想要 Foo
code> FooID 被视为同一组。我需要在 Foo
类中重写哪些方法?
总结:我想将 Stuff
对象放入列表中,按 Foo
对象进行分组。 Stuff
对象将有一个 FooID
来将它们链接到它们的类别。
Equals()解决方案
code>。如果两个事物相等( 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;
$ b最后,另一种方法是提供一个 IEqualityComparer< T>
做同样的事情。
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.
解决方案 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.
这篇关于将对象的字段用作通用字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!