简体   繁体   English

C#运算符重载==和pragma警告660和661在不相关时不覆盖Equals和GetHashCode

[英]C# operator overloading == and pragma warnings 660 & 661 not overriding Equals and GetHashCode when irrelevant

Why does the C# compiler complain with pragma warning 660 & 661 为什么C#编译器会抱怨pragma警告660和661

  • "FooClass" defines operator == or operator != but does not override Object.Equals(object o) “FooClass”定义operator ==或operator!=但不覆盖Object.Equals(object o)
  • "FooClass" defines operator == or operator != but does not override Object.GetHashCode() “FooClass”定义operator ==或operator!=但不覆盖Object.GetHashCode()

When adding additional operators, such as: 添加其他运算符时,例如:

public static bool operator ==(FooClass foo, string fooId)

I am not specifying 没有具体说明

public static bool operator ==(FooClass foo, FooClass foo2)

Which this would make sense to override Object.Equals and GetHashCode. 这有意义覆盖Object.Equals和GetHashCode。

Is this just a limitation in the compiler that it's not properly checking the arguments specified in the operator? 这只是编译器中的一个限制,它没有正确检查运算符中指定的参数吗?

The general guideline is doing foo == bar should return the same result as foo.Equals(bar) , that is the reason for the warning. 一般准则是foo == bar应该返回与foo.Equals(bar)相同的结果,这就是警告的原因。 It is a guideline, not a requirement, and that is why it is a warning instead of a error. 这是一个指导原则,而不是一项要求,这就是为什么它是警告而不是错误。

The 2nd warning is because of the rule that if(foo.Equals(bar)) foo.GetHashCode() == bar.GetHashCode() . 第二个警告是因为if(foo.Equals(bar)) foo.GetHashCode() == bar.GetHashCode() If two objects are equal, their hash codes should also be equal. 如果两个对象相等,则它们的哈希码也应该相等。 Many things in the .NET framework and 3rd party libraries rely on this so if you don't do it things like Dictionary that use GetHashCode() for lookups is going to break. .NET框架和第三方库中的许多东西都依赖于此,所以如果你不这样做,像Dictionary这样使用GetHashCode()进行查找的东西就会破坏。

So if I can do 所以如果我能做到的话

FooClass foo = new FooClass("Foo");
if(foo == "Foo")
{
   //...
}

I expect to be able to do 我希望能够做到

FooClass foo = new FooClass("Foo");
Hashtable hash = new Hashtable();
hash.Add(foo, "Bar");
var result = hash["Foo"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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