How to best implement Equals for custom types?

前端 未结 10 721
春和景丽
春和景丽 2020-11-28 08:41

Say for a Point2 class, and the following Equals:

public override bool Equals ( object obj )

public bool Equals ( Point2 obj )

This is the

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 09:20

    • Define what the identity means.. if reference identity then the default inherited equals will work.
    • If a value type (and thus value identity) you need to define.
    • If a class type, but has value semantics then define.

    Likely you want to both override Equals(object) and define Equals(MyType) because the latter avoids boxing. And override the equality operator.

    .NET Framework Guidelines book (2nd ed) has more coverage.

提交回复
热议问题