重载运算符 == C#

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);
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值