为什么XName相等运算符似乎引用自身?

时间:2016-08-04 14:59:55

标签: c# operator-overloading equality

我想知道如何为XName定义相等,并注意到相等运算符似乎引用自身(当使用ILSpy 2.4.0.1963查看反编译的C#时)

public static bool operator ==(XName left, XName right)
{
    return left == right;
}

1 个答案:

答案 0 :(得分:2)

这是您的反编译器中的错误。

它实际上将两个操作数都转换为object以通过引用进行比较。

请参阅actual source

    // The overloads of == and != are included to enable comparisons between
    // XName and string (e.g. element.Name == "foo"). C#'s predefined reference
    // equality operators require one operand to be convertible to the type of
    // the other through reference conversions only and do not consider the
    // implicit conversion from string to XName.

    /// <summary>
    /// Returns a value indicating whether two instances of <see cref="XName"/> are equal.
    /// </summary>
    /// <param name="left">The first XName to compare.</param>
    /// <param name="right">The second XName to compare.</param>
    /// <returns>true if left and right are equal; otherwise false.</returns>
    /// <remarks>
    /// This overload is included to enable the comparison between
    /// an instance of XName and string.
    /// </remarks>
    public static bool operator ==(XName left, XName right) {
        return (object)left == (object)right;
    }