C#operator == check for null

时间:2014-06-19 22:55:50

标签: c# operator-overloading

我创建了一个具有==运算符功能的类,但是我想测试这些值是否为null,但是当我测试这个时,我开始一个永无止境的循环。如何在不创建永无止境的循环的情况下执行以下操作?

public struct MyClass
{
    private string Value;

    public static bool operator ==(MyClass left, MyClass right)
    {
        if (left == null && right == null)
            return true;
        if (left == null || right == null)
            return false;
        return left.Equals(right);
    }
}

1 个答案:

答案 0 :(得分:1)

找到答案

public struct MyClass
{
    private string Value;

    public static bool operator ==(MyClass left, object right)
    {
        // Test if both are null or the same instance, then return true
        if (ReferenceEquals(left, right))
            return true;

        // If only one of them null return false
        if (((object)left == null) || ((object)right == null))
            return false;

        // Test value
        return left.Equals(right);
    }
}