【问题标题】:how to avoid stackoverflow in == overload [duplicate]如何避免==重载中的stackoverflow [重复]
【发布时间】:2014-09-05 22:03:52
【问题描述】:

这是我在类中对 == 和 != 运算符的实现。

 public class MyClass 
    {
        public int         FirstField            { get; set; }
        public int         SecondField            { get; set; }

        public static bool operator ==(MyClass first, MyClass second)
        {
            if (first == null && second == null)
                return true;
            else if (first == null || second == null)
                return false;
            else
            {
                if (first.FirstField == second.FirstField && first.SecondField == second.SecondField)
                    return true;
                else
                    return false;
            }
        }

        public static bool operator !=(MyClass first, MyClass second)
        {
            return !(first == second);
        }
    }

在代码中的其他地方,我有以下两个用于 == 和 != 比较的实例。

MyClass class1;
MyClass class2;

if (class1 == null || (class1 != null && class1 != class2)  )

问题是,当上面的行被调用时,我在下一行得到一个 stackoverflow 异常。

if (first == null && second == null)

What am I doing wrong here?  

【问题讨论】:

    标签: .net c#-3.0 equality


    【解决方案1】:

    运算符定义中的first == null 重新调用运算符 => 堆栈溢出。

    您要检查的是 reference 是否相等,这与重载时的“==”不同。

    更换你的

            if (first == null && second == null)
                return true;
            else if (first == null || second == null)
                return false;
    

    通过

    if (ReferenceEquals(first,second))
       return true;
    if(ReferenceEquals(first,null) || ReferenceEquals(second,null))
       return false;
    

    侧节点:您的最后一个“else”主体不需要嵌套的“if”。可以换成return first.FirstField == second.FirstField && first.SecondField == second.SecondField;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多