这是笔者在写C#运算符重载时的报错!
这个报错意思是:
未处理的异常。未将对象引用设置为对象的实例
这发生在我的代码 return t2.Equal(t1)行上
public static bool operator ==(Test24 t1,Test24 t2)
{
return t2.Equals(t1);
}
下面是完整的代码
测试类
class Test24
{
public void MyFun()
{
Test24 t = new Test24();
if (t==null)
{
Console.WriteLine("t为空");
}
else
{
Console.WriteLine("t不为空");
}
}
public static bool operator ==(Test24 t1,Test24 t2)
{
return t2.Equals(t1);
}
public static bool operator !=(Test24 t1, Test24 t2)
{
return !(t1==t2);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
}
运行类
class Program
{
static void Main(string[] args)
{
Test24 t= new Test24();
t.MyFun();
Console.ReadLine();
}
}
通过报错分析,在编写相等运算符时,由于程序的逻辑判断不够严谨,从而造成程序本身存在一定的欠缺,所以改进的办法就是加强逻辑判断的严谨性。改进后的代码如下:
public static bool operator ==(Test24 t1, Test24 t2)
{
if ((t2 as object) == null)
{
return (t1 as object) == null;
}
else
{
return t2.Equals(t1);
}
}