导航

C# ==和 != 操作符重载注意事项

Posted on 2010-09-25 14:51  REMING  阅读(260)  评论(0编辑  收藏  举报

1. 重载其中一个必须两个都要重载。

2. 不能在方法中使用==或!==运算符;

代码
 public static bool operator ==(TestRefOperatorEquals te1, TestRefOperatorEquals te2)
        {
            
/* 以下代码是错误的,因为操作符已被重载
            if (te1==null && te2==null)
            {
                return true;
            }
            if (te1 !=null )
            {
                return te1.Equals(te2);
            }
            return false;
            
*/
            
//正确的方法
            return object.ReferenceEquals(te1, te2);
        }

3.对于值类型和引用类型的处理是不同的