怎么我定义operator ==后,使用一直报错?

tangxu12 2012-03-08 09:46:14
我定义了
public static bool operator ==(MyShape lhs, object rhs).....
public static bool operator !=(MyShape lhs, object rhs).....

编译没有问题,怎么一和NULL比较就报错?
MyShape shape1 = null;
...
if (shape1 == null)...
...全文
143 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
tangxu12 2012-03-08
  • 打赏
  • 举报
回复
gomoku
谢谢!!!!

按你的方法解决了!!

object.ReferenceEquals
不是
object.ReferenceEqual

谢谢!!!
分全给你
meatbird 2012-03-08
  • 打赏
  • 举报
回复
嗯,手边刚刚好有这本书
1. 先重写Equals
2. 再重写GetHashCode
3. 再重写 == 和 !=
是推荐的做法,否则会有某些缺陷产生
以下是我写的,不一定非常完善,供参考,可以解决 == null 的问题

public override bool Equals(object obj)
{
//Check for null
if (obj == null)
return false;
if (obj.GetType() != typeof(BasicQuoteInfo))
{
return false;
}
return this.Equals(obj as BasicQuoteInfo);
//这个Equals 是另外重新写的,真正的同类比较
}

/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="q1">The q1.</param>
/// <param name="q2">The q2.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator ==(BasicQuoteInfo q1, BasicQuoteInfo q2)
{
if (((object)q1 == null && (object)q2 != null) || ((object)q1 != null && (object)q2 == null))
return false;
if ((object)q1 == null && (object)q2 == null)
return true;
return q1.Equals(q2);
}
threenewbee 2012-03-08
  • 打赏
  • 举报
回复
你要是真的想重写==,先看看《C#高效编程》中的某一个专题(记不得具体编号了),专门讲这些原则,看明白了再写。

大致原则包括保证数学上的自反、对称和传递特性,同时配套需要统一Equals方法和GetHashCode方法。
gomoku 2012-03-08
  • 打赏
  • 举报
回复
public static bool operator ==(MyShape lhs, object rhs)
{
if( object.ReferenceEqual(lhs, rhs) ) return true;
if( object.ReferenceEqual(lhs,null) || object.ReferenceEqual(rhs,null) ) return false;
...
}
public static bool operator !=(MyShape lhs, object rhs)
{
return !(lhs == rhs);
}
threenewbee 2012-03-08
  • 打赏
  • 举报
回复
看你怎么实现的operator ==,以及报什么错。

实际上你不应该乱重写等号。重写运算符是有原则的。
tangxu12 2012-03-08
  • 打赏
  • 举报
回复
MyShape 是类

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧