重载运算符 == C#

来源:互联网 发布:网页动画制作软件 编辑:程序博客网 时间:2024/04/30 07:42
public override bool Equals(LotKeyInfo other){    return otherKey != null &&        (this.CompanyID == otherKey.CompanyID && this.LotID == otherKey.LotID);}public static bool operator ==(LotKeyInfo key1, LotKeyInfo key2){    object o1 = key1;    object o2 = key2;    if (o1 == null || o2 == null)    {if(o1 == null && o2 == null)return true;        return false;    }    return key1.Equals(key2);}public static bool operator !=(LotKeyInfo key1, LotKeyInfo key2){    return !(key1 == key2);}

看起来很简单,不过这个过程却是花费了一些功夫,注意要点:

1. 如果重载运算符 == , 那么同时也要重载 重载 !=

2. 在 == 的函数里面,开始犯了一个错误,就是在尝试去判断传进来的参数是否为 null 时,用了这种办法 

if(key1 == null || key2 == null)  return false;

结果进入死循环,因为它调用了自己!

尝试去用 null == key1 判断,还是死循环

StatckOverflow 上有另外一种写法判断 null ,也可以参考:

public static bool operator ==(Person person1, Person person2){    if (object.ReferenceEquals(person1, null))    {         return object.ReferenceEquals(person2, null);    }    return person1.Equals(person2);}


0 0