简体   繁体   English

我应该为对象和MyType覆盖==吗?

[英]Should I override == for object and MyType?

I have a struct called MyType that implements IEquatable<MyType> . 我有一个名为MyTypestruct ,该struct实现了IEquatable<MyType>

I have implemented operator ==(MyType x, MyType y) , but should I also implement operator ==(MyType x, object y) for the case below? 我已经实现了operator ==(MyType x, MyType y) ,但是在以下情况下我是否也应该实现operator ==(MyType x, object y)

For example: 例如:

public static bool operator ==(MyType x, object y)
{
    if (y is MyType)
    {
        return x == (MyType)y;
    }

    return false;
}

Usage: 用法:

var a = new MyType();
object b = new MyType();

var result = (a == b); // ?

No CTS type does this, as far as I know. 据我所知,没有CTS类型可以做到这一点。 Good examples include Decimal and DateTime , which both only implement equality for their respective types and not for their base types or interfaces. 很好的例子包括DecimalDateTime ,它们都只对它们各自的类型实现相等,而不对它们的基本类型或接口实现相等。

Moreover, this implementation may encourage comparing virtually any type with your struct, even other structs, and someone who might use your code in the future may think comparing MyType with MyOtherType could make sense, while all it would do is boxing the other type and then returning false. 此外,此实现可能会鼓励几乎将任何类型与您的结构(甚至其他结构)进行比较,并且将来可能使用您的代码的人可能会认为将MyTypeMyOtherType进行比较可能是有道理的,而要做的就是将其他类型装箱返回假。 Also one usually interprets == on object as meaning reference equality. 还有一种通常将object ==解释为引用相等。

In addition, you should overload the op_Equality and op_Inequality operators. 另外,您应该重载op_Equalityop_Inequality运算符。 This ensures that all tests for equality return consistent results. 这样可以确保所有相等性测试均返回一致的结果。

The documentation does not tell which equality operators you should overload, and the second sentence may actually be interpreted in the terms of MyType == object being consistent with MyType.Equals(object) . 文档没有告诉您应该重载哪个相等运算符,并且第二句话实际上可以用与MyType.Equals(object)一致的MyType == object的术语来解释。 However, the fact that no .NET types actually do this and that it leads to confusion are sufficient to say that it is not a good practice. 但是,实际上没有任何.NET类型会这样做,并且会引起混乱,这一事实足以说明这不是一个好习惯。

If other types can be treated as MyType , overload the explicit or implicit cast. 如果可以将其他类型视为MyType ,请重载显式或隐式强制转换。

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

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