在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?
鉴于以下课程
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经覆盖了该Equals方法,因为它Foo代表了Foos表的一行.哪个是覆盖的首选方法GetHashCode?
覆盖为什么重要GetHashCode?
我希望我的Food类能够在它等于另一个实例时进行测试Food.我稍后会对List使用它,我想使用它的List.Contains()方法.我应该实施IEquatable<Food>还是仅仅覆盖Object.Equals()?来自MSDN:
此方法通过使用默认的相等比较器来确定相等性,由对象的T的IEquatable.Equals方法的实现(列表中的值的类型)定义.
所以我的下一个问题是:.NET框架的哪些函数/类可以使用Object.Equals()?我应该首先使用它吗?
我试图理解IEqualityComparer接口的GetHashCode方法的作用.
以下示例来自MSDN:
using System;
using System.Collections.Generic;
class Example {
static void Main() {
try {
BoxEqualityComparer boxEqC = new BoxEqualityComparer();
Dictionary<Box, String> boxes = new Dictionary<Box,
string>(boxEqC);
Box redBox = new Box(4, 3, 4);
Box blueBox = new Box(4, 3, 4);
boxes.Add(redBox, "red");
boxes.Add(blueBox, "blue");
Console.WriteLine(redBox.GetHashCode());
Console.WriteLine(blueBox.GetHashCode());
}
catch (ArgumentException argEx) {
Console.WriteLine(argEx.Message);
}
}
}
public class Box {
public Box(int h, int l, int w) {
this.Height = h;
this.Length = l;
this.Width = w;
}
public int …Run Code Online (Sandbox Code Playgroud) 当我使用字典有时我必须更改默认的等于意思,以便比较键.我看到如果我在键的类上重写Equals和GetHashCode,或者我创建了一个实现IEqualityComparer的新类,我有相同的结果.那么使用IEqualityComparer和Equals/GethashCode Override有什么区别?两个例子:
class Customer
{
public string name;
public int age;
public Customer(string n, int a)
{
this.age = a;
this.name = n;
}
public override bool Equals(object obj)
{
Customer c = (Customer)obj;
return this.name == c.name && this.age == c.age;
}
public override int GetHashCode()
{
return (this.name + ";" + this.age).GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
Customer c1 = new Customer("MArk", 21);
Customer c2 = new Customer("MArk", 21);
Dictionary<Customer, string> d = …Run Code Online (Sandbox Code Playgroud) c# ×4
.net ×3
gethashcode ×3
equality ×2
equals ×2
hashcode ×2
algorithm ×1
iequatable ×1
overriding ×1