c# - 如何抑制 "possible unintended reference comparison"警告?

标签 c# .net warnings suppress-warnings

在这种情况下,我得到了一个“可能是意外的引用比较”:

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/

相关文章:

asp.net - 遵循教程后的ASP.Net警告和错误-需要帮助

c# - 如何在事件外使用事件参数

c# - 从 C# 中的另一个表单获取组合框值

c# - 即使我添加了AllowLoadLocalInfile,该MySQL版本也不允许使用该命令

c# - Sitecore 创建包含字段 [] 的项目

.net - 类级验证

c# - CMake - 将预建库链接到 C# 项目

c# - 将按键事件绑定(bind)到 WPF 中的 ListViewItem

OCaml - 来自类型别名的混淆(警告 40)

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP