检查实现IEqualityComparer<T>的类的null相等性的干净方法是什么?

c#

这就是我可以想出的检查空相等性的方法。它有效,但它看起来像 Shreak。以下内容适用于本示例:

x != null and y == null returns false;
x == null and y != null returns false;
x == null and y == null returns true;
x.ToString() == y.ToString() returns true;

我想我可以编写上面的代码,但我仍然觉得有一种更简洁的方法可以解决它。

public bool Equals(ConvertibleData x, ConvertibleData y)
{
    if (x == null)
    {
        if (y == null)
        {
            return true;
        }

        return false;
    }

    if (y == null)
    {
        return false;
    }

    return x.ToString() == y.ToString(); //Disregard the ToString, this coult be any comparer validation
}

回答

我通常使用这种模式,其中比较数可以为空:

public bool Equals(ConvertibleData? x, ConvertibleData? y)
{
    if (ReferenceEquals(x, y))
        return true;

    if (x is null || y is null)
        return false;

    return x.ToString() == y.ToString(); //Disregard the ToString, this coult be any comparer validation
}


以上是检查实现IEqualityComparer<T>的类的null相等性的干净方法是什么?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>