【问题标题】:C# operator == check for null [duplicate]C# 运算符 == 检查 null [重复]
【发布时间】:2014-08-10 15:14:59
【问题描述】:

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

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

【问题讨论】:

  • @JeffMercado OP 在声明中使用了==,有效地导致了无休止的递归和最终的StackOverflowException
  • +1 表示好问题,-1 表示重载 == 引用类型(这似乎不是一成不变的,请参阅 msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
  • @vesan 谢谢你的提示,我现在已经成功了:D

标签: c# operator-overloading


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2016-09-26
    相关资源
    最近更新 更多