这是一个运算符重载
(==的重载,而不是ReferenceEquals
方法的重载)来检查两个Shop
类型实例是否具有相等的引用(也就是它们是否引用相同的内存地址)。
bool result = shop1 == shop2; //shop1 and shop2 are of type Shop
在声明 ==
运算符时,您还需要重载其匹配(或对立)运算符 !=
:
public static bool operator ==(Shop lhs, Shop rhs) {
if (Object.ReferenceEquals(lhs, null)) {
if (Object.ReferenceEquals(rhs, null)) {
return true;
}
return false;
}
return lhs.Equals(rhs);
}
public static bool operator !=(Shop lhs, Shop rhs) {
if (Object.ReferenceEquals(lhs, null)) {
if (Object.ReferenceEquals(rhs, null)) {
return false;
}
return true;
}
return !lhs.Equals(rhs);
}
值得注意的是,代码中使用
Object.ReferenceEquals(lhs, null)
而不是
lhs == null
,因为后者会导致另一个重载的
==
被调用,直到
无限递归,从而导致
StackOverflowException
。
它们的使用方式如下:
Shop shop1 = new Shop();
Shop shop2 = new Shop();
bool result = shop1 == shop2; //this will return false, since lhs and rhs referring to two different memory address
shop2 = shop1;
result = shop1 == shop2; //this will return true, referring to the same memory location
shop1 = null;
shop2 = null;
result = shop1 == shop2; //this will return true, both are null
理解这一点,你甚至可以创建这样的东西:
public struct MyCrazyInt{
private int Value { get; set; }
public MyCrazyInt(int value) :this() {
Value = value;
}
public bool Equals(MyCrazyInt otherCrazy) {
return this.Value != otherCrazy.Value;
}
public static MyCrazyInt operator +(MyCrazyInt lhs, MyCrazyInt rhs) {
int lhsVal = lhs.Value;
int rhsVal = rhs.Value;
return new MyCrazyInt(lhsVal - rhsVal);
}
public static MyCrazyInt operator -(MyCrazyInt lhs, MyCrazyInt rhs) {
int lhsVal = lhs.Value;
int rhsVal = rhs.Value;
return new MyCrazyInt(lhsVal + rhsVal);
}
public override string ToString() {
return Value.ToString();
}
}
然后像这样使用它
MyCrazyInt crazyInt1 = new MyCrazyInt(5);
MyCrazyInt crazyInt2 = new MyCrazyInt(3);
MyCrazyInt crazyInt3 = crazyInt1 - crazyInt2; //this will return 8
crazyInt3 = crazyInt1 + crazyInt2; //this will return 2
Object.ReferenceEquals
检查引用是否相等... ;) 换句话说,它检查对象是否具有相同的对象,即在物理内存地址方面。 - RobReferenceEquals
,那么这将是重载(在这种情况下是个坏主意,但对于其他方法很有用)。 - Jon Hanna