如何抑制 "possible unintended reference comparison" 警告?
How to suppress "possible unintended reference comparison" warning?
在这种情况下我得到 "possible unintended reference comparison":
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
to suppress warning in this situation, using ReferenceEquals
提供了更好的选择:
public override bool Equals(Child other) {
return ReferenceEquals(parent, other.parent) && index == other.index;
}
除了消除警告之外,此选项还让阅读您代码的其他程序员清楚地知道引用比较不是错误。
在这种情况下我得到 "possible unintended reference comparison":
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
to suppress warning in this situation, using ReferenceEquals
提供了更好的选择:
public override bool Equals(Child other) {
return ReferenceEquals(parent, other.parent) && index == other.index;
}
除了消除警告之外,此选项还让阅读您代码的其他程序员清楚地知道引用比较不是错误。