手机
当前位置:查字典教程网 >编程开发 >C#教程 >C#中重载相等(==)运算符示例
C#中重载相等(==)运算符示例
摘要:运算符重载一直是一个很诡异事情,因为在写代码的时候,不知道某个运算符有没有被重载过。在C++里面,运算符重载可以写在类的外面,当intell...

运算符重载一直是一个很诡异事情,因为在写代码的时候,不知道某个运算符有没有被重载过。在 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 不建议重载==,但是不建议并不代表不能用吧,这个设计太挫了…

【C#中重载相等(==)运算符示例】相关文章:

C# 一个WCF简单实例

C#几种获取网页源文件代码的实例

C#中一些字符串操作的常用用法

C#中隐式运行CMD命令行窗口的方法

C#基础 延迟加载介绍与实例

C#中38个常用运算符的优先级的划分和理解

C#重启远程计算机的代码

c#中抽象类和接口的详细介绍

C# 中的??操作符浅谈

c#中返回文章发表的时间差的示例

精品推荐
分类导航