(C#)重载==运算符时出现问题

Jor*_*nco 4 c# null operator-overloading

我在我的类上重载了==运算符,如下所示:

public static bool operator ==(Table pt1, Table pt2) {
    return Compare(pt1, pt2) == 0 && pt1.TableName == pt2.TableName;
}
Run Code Online (Sandbox Code Playgroud)

比较将像strcmp在c ++中一样工作,返回一个整数.问题是,如果我执行if(MY_CLASS == null),它将调用我的==运算符,从而调用我的Compare函数.什么是alternatiev?检查pt1和pt2以查看它们是否为空?或者只是在pt2?

Luk*_*ane 12

您应该查看Microsoft的实现'=='运算符的指南以及覆盖'Equals()'的指南.

根据他们的例子,您需要以下内容:

public static bool operator ==(Table a, Table b)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(a, b))
    {
        return true;
    }

    // If one is null, but not both, return false.
    if (((object)a == null) || ((object)b == null))
    {
        return false;
    }

    // Return true if the fields match:
    return Compare(a, b) == 0 && a.TableName == b.TableName;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你明白我的意思,我要么在两个地方使用object.ReferenceEquals,要么在两个地方使用强制转换. (4认同)