标签:使用 ar sp c on r ad line new
static void Main(string[] args)
        {
            Test t = new Test();
            t.MyFun();
            Console.ReadLine();
}
class Test
        {
            //自定义方法用来测试重载运算符
            public void MyFun()
            {
                Test t = new Test();
                if (t == null)  Console.WriteLine("t为空!");
                Console.WriteLine("t不为空!");               
            }
            //重载相等运算符
            public static bool operator ==(Test t1, Test t2)
            {
                return t2.Equals(t1);
            }
            //重载不等运算符
            public static bool operator !=(Test t1, Test t2)
            {
                return !(t1==t2);
            }
            //重写HashCode方法
            public override int GetHashCode()
            {
                return base.GetHashCode();
            }
            //重写Equals方法
            public override bool Equals(object obj)
            {
                return base.Equals(obj);
            }
}
分析:调试中发现t2为空。当程序判断引用变量t的值是否等于空时,就会使用相等运算符,进一步就会调用重载相等运算符所对应的方法,这样t和null就会作为该方法的参数被传入,而null恰好被传递给参数t2,而且重载方法也会调用本方法,死循环。
解决:
 public static bool operator ==(Test t1, Test t2)
            {
                if ((t2 as object) == null)
                {
                    return (t1 as object) == null;
                }
                else
                {
                    return t2.Equals(t1);
                }
            }
标签:使用 ar sp c on r ad line new
原文地址:http://www.cnblogs.com/vakeynb/p/vakey.html