需要在结构中覆盖哪些内容以确保平等正常运行? [英] What needs to be overridden in a struct to ensure equality operates properly?
本文介绍了需要在结构中覆盖哪些内容以确保平等正常运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所说:我需要覆盖 ==
运算符吗?.Equals()
方法怎么样?我有什么遗漏吗?
As the title says: do I need to override the ==
operator? how about the .Equals()
method? Anything I'm missing?
推荐答案
来自 msdn 的示例
An example from msdn
public struct Complex
{
double re, im;
public override bool Equals(Object obj)
{
return obj is Complex c && this == c;
}
public override int GetHashCode()
{
return re.GetHashCode() ^ im.GetHashCode();
}
public static bool operator ==(Complex x, Complex y)
{
return x.re == y.re && x.im == y.im;
}
public static bool operator !=(Complex x, Complex y)
{
return !(x == y);
}
}
这篇关于需要在结构中覆盖哪些内容以确保平等正常运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文