简体   繁体   中英

How to suppress “possible unintended reference comparison” warning?

I get a "possible unintended reference comparison" in this situation:

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;
        }
    }
    ...
}

However, reference comparison is fully intentional in this situation, because I want Child objects of different parents to be considered unequal to each other. How do I tell the compiler about my intention, and suppress the warning?

Although you could use #pragma to suppress warning in this situation, using ReferenceEquals provides a better alternative:

public override bool Equals(Child other) {
    return ReferenceEquals(parent, other.parent) && index == other.index;
}

In addition to silencing the warning, this option makes it clear to other programmers reading your code that reference comparison is not a mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM