需要在结构中被重写,以确保平等可以正常运行呢?重写、正常运行、平等、结构

2023-09-02 11:51:25 作者:▍我的世界不能没有你

正如标题所说:我是否需要重写 == 运营商?如何对 .Equals()的方法?任何事情我丢失吗?

As the title says: do i need to override the == operator? how about the .Equals() method? Anything i'm missing?

推荐答案

从MSDN的例子

public struct Complex 
{
   double re, im;
   public override bool Equals(Object obj) 
   {
      return obj is Complex && this == (Complex)obj;
   }
   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);
   }
}
 
精彩推荐
图片推荐