我试图为自定义类编写运算符重载,并且不知道如何处理空值比较.
Class Customer { int id; public static bool operator ==(Customer a, Customer b) { //When both a and b are null don't know how to compare as can't use == in here as //it will fall into loop } }
问题是当a和b都为null时结果为true但不确定如何在不使用==的情况下检查它.
if (Object.ReferenceEquals(a,b)) return true;
ReferenceEquals()检查它们是否指向完全相同的对象(或者它们都是null)
(作为一般规则,最好通过调用ReferenceEquals来启动Equals()方法,特别是如果方法的其余部分很复杂的话.它会使事情a==a
快速返回true,而不必检查每个元素.)