当前位置: 移动技术网 > IT编程>开发语言>c# > C#中重载相等(==)运算符示例

C#中重载相等(==)运算符示例

2019年07月18日  | 移动技术网IT编程  | 我要评论
运算符重载一直是一个很诡异事情,因为在写代码的时候,不知道某个运算符有没有被重载过。在 c++ 里面,运算符重载可以写在类的外面,当 intellisense 不工作的时候

运算符重载一直是一个很诡异事情,因为在写代码的时候,不知道某个运算符有没有被重载过。在 c++ 里面,运算符重载可以写在类的外面,当 intellisense 不工作的时候,找到一个运算符的重载函数是一件相当头疼的事情。这个问题在 c# 中改善了不少,因为运算符重载一定要写在类内,而且 intellisense 很强大。不过另一个问题又产生了……

先来看 c++ 中的“==”重载:

struct a{
 int x;
 int y;
};
 
inline
bool operator == (const a& a, const a& b){
 return a.x == b.x && a.y == b.y;
}

上面这段代码中,由于声明的关系,a 和 b 永远不可能为 null,所以直接调用 a.x 和 b.x 是没有问题的。

而在 c# 中:

struct a
{
 public int x, y;
 public static bool operator ==(a a, a b)
 {
  return a.x == b.x && a.y == b.y;
 }
 public static bool operator !=(a a, a b)
 {
  return !(a == b);
 }
}

这段代码是没问题的,因为 a 是 struct,而 struct 不可能为 null。但换成 class 就有问题了,比如:

class a
{
 public int x, y;
 public static bool operator == (a a, a b)
 {
  if (a == null && b == null)
  {
   return true;
  }
  if (a == null || b == null)
  {
   return false;
  }
  return a.x == b.x && a.y == b.y;
 }
 public static bool operator != (a a, a b)
 {
  return !(a == b);
 }
}

由于 reference type 可以为 null,所以要先检查 a 和 b 是不是 null,但是“a == null”这一句又会去调用“operator ==”,于是就无限递归下去了……想了很久都没想出来变通的方法,而且 system.string 的实现也很诡异:

public static bool operator == (string a, string b)
{
 return equals(a, b);
}
public static bool equals (string a, string b)
{
 return ((a == b) || (((a != null) && (b != null)) && equalshelper(a, b)));
}

看上去也会无限递归的(reflector 出来的,不一定准),很神奇……

虽然对于 referece type 不建议重载==,但是不建议并不代表不能用吧,这个设计太挫了…

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网