自己实现值类型的Equals和GetHashCode

Dictionary cacheIndex = new Dictionary();
在操作数据的时候,会调用默认的比较器


image.png

值类型的比较会进行拆装箱的操作,所以我们可以自己实现比较器和hashcode。注意:相同值必须要返回相同的hashcode才可以。
public class selfEqualCmp: IEqualityComparer
{
public bool Equals(int x, int y)
{
return x == y;
}
public int GetHashCode(int obj)
{
return obj;
}
}
selfEqualCmp cmpar = new selfEqualCmp();
Dictionary cacheIndex = new Dictionary(cmpar);

image.png

你可能感兴趣的:(自己实现值类型的Equals和GetHashCode)