需要在结构中被重写,以确保平等可以正常运行呢? [英] What needs to be overriden in a struct to ensure equality operates properly?

查看:149
本文介绍了需要在结构中被重写,以确保平等可以正常运行呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说:我是否需要重写 == 运营商?如何对 .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);
   }
}

这篇关于需要在结构中被重写,以确保平等可以正常运行呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆