[Serializable]
public class ComplexArray
{
#region Attributes
/// <summary>
/// Array Size
/// </summary>
protected int m_iSize;
/// <summary>
/// Real part of the data
/// </summary>
protected double[] m_dReal;
/// <summary>
/// Imaginary part of the data
/// </summary>
protected double[] m_dImag;
#region Construction
/// <summary>
/// Default constructor
/// </summary>
public ComplexArray()
{
}
public override bool Equals(object o)
{
if (this == (ComplexArray)o)
return true;
else
return false;
}
public static bool operator ==(ComplexArray src1, ComplexArray src2)
{
if (src1.m_iSize != src2.m_iSize)
return false;
for (int ii = 0; ii < src1.m_iSize; ii++)
{
if (src1.Real[ii] != src2.Real[ii])
return false;
if (src1.Imag[ii] != src2.Imag[ii])
return false;
}
return true;
}
public static bool operator !=(ComplexArray src1, ComplexArray src2)
{
if (src1 == src2)
return false;
else
return true;
}
}
我创建了一个名为复数数组的类,该类的目的是保存实数和虚数,并且不同的运算符已被重载,例如 +,*,!=,==
假设某个函数返回这个类的实例。
ComplexArray array = GetValue();
我想检查引用是否有效...
if(array != null)
{
//proceed further....
}
问题:当根据空值检查该值时,会发生异常,因为内部 != 重载函数调用 ==。
运算符重载时如何避免这种情况?或者如何使运算符 != 或 == 检查空值并返回正确的值(真或假)