简体   繁体   中英

In a struct, is it valid to implement operator== via Equals, but not override Equals and GetHashCode?

Is this valid?

public struct MyStruct
{
    public int Foo { get; set; }

    public static bool operator ==(MyStruct a, MyStruct b)
    {
        return a.Equals(b);
    }

    public static bool operator !=(MyStruct a, MyStruct b)
    {
        return !a.Equals(b);
    }
}

(I know it's slightly inefficient because Object.Equals uses reflection for value types by default. But is it valid?)

I'm asking because ReSharper highlights it and warns me that MyStruct defines operator '==' or operator '!=' but does not provide 'Object.Equals(object o)' and 'Object.GetHashCode()' .

我觉得可能很有趣。

Valid? Yes. But it doesn't buy you anything.

It's valid, in terms of the fact that it compiles. But it's "invalid" in the sense that it breaks all expectations of users of your class - the framework design guidelines specify that you shouldn't implement functionality that only exists in operator overloads - that such methods should be accessible in other ways. And the standard is that Object.Equals and operator== implement the same functionality.

(Can only find the 1.1 version of the guidelines at the moment) :

Provide alternate signatures. Most languages do not support operator overloading. For this reason, it is a CLS requirement for all types that overload operators to include a secondary method with an appropriate domain-specific name that provides the equivalent functionality. It is a Common Language Specification (CLS) requirement to provide this secondary method. The following example is CLS-compliant.

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