在这种情况下,我得到了一个“可能是意外的引用比较”:
class Parent {
class Child : IEquitable<Child> {
private readonly int index;
private readonly Parent parent;
internal Child(Parent parent, int index) {
this.parent = parent;
this.index = index;
}
public override int GetHashCode() {
return parent.GetHashCode()*31 + index.GetHashCode();
}
public override bool Equals(object obj) {
Child other = obj as Child.
return other != null && Equals(other);
}
public override bool Equals(Child other) {
// The warning I get is on the next line:
return parent == other.parent && index == other.index;
}
}
...
}
但是,在这种情况下,引用比较是完全有意的,因为我希望不同父对象的 Child
对象被认为彼此不相等。我如何告诉编译器我的意图,并抑制警告?
最佳答案
尽管您可以使用 #pragma
在这种情况下抑制警告,使用 ReferenceEquals
提供了一个更好的选择:
public override bool Equals(Child other) {
return ReferenceEquals(parent, other.parent) && index == other.index;
}
除了消除警告之外,此选项还让阅读您代码的其他程序员清楚地知道引用比较不是错误。
关于c# - 如何抑制 "possible unintended reference comparison"警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35293658/