gpt4 book ai didi

c# - 应该是 IEquatable's Equals() be implemented via IComparable' s CompareTo()?

转载 作者:可可西里 更新时间:2023-11-01 07:55:23 26 4
gpt4 key购买 nike

我一直在互联网上寻找答案,但我找到的是:

编辑:添加了一些响应答案的项目

  • 对于IEquatable

    • 我应该重载 Equals() , GetHashCode() , ==!=一起。
    • 我应该通过实现 != 来减少冗余通过== .
    • 我应该结束这个类
  • 对于 IComparable

    • 我应该重载 Equals() , GetHashCode() , < , > , <=>=一起。
    • 实际上建议在这样做时实现 IEquatable
    • 重载 IComparable 的非泛型版本
    • CompareTo() == 0应该是 Equals() == true

所以我一直在想这个:

public bool Equals(T other)
{
if ((object)other == null)
{
return false;
}

return CompareTo(other) == 0;
}

我是不是忽略了什么或者这样可以吗?

最佳答案

According to Eric Lippert ,微软 C# 编译器团队的前开发人员:

  • There are nine ways to do a comparison in C#: < <= > >= == != object.Equals(object) IEquatable<T>.Equals(T) IComparable<T>.CompareTo(T)
  • Ideally these should all be consistent with each other. That is, if x == y is true then x < y is false but x <= y and x.Equals(y) are true and x.CompareTo(y) is zero, and so on.

所以,在他看来,“理想情况下”x.CompareTo(y) == 0暗示 x.Equals(y) == true反之亦然。

然后 Eric 提供了一个使用私有(private)辅助方法实现一切的示例:

public int CompareTo(Natural x) { return CompareTo(this, x); }
public static bool operator <(Natural x, Natural y) { return CompareTo(x, y) < 0; }
public static bool operator >(Natural x, Natural y) { return CompareTo(x, y) > 0; }
public static bool operator <=(Natural x, Natural y) { return CompareTo(x, y) <= 0; }
public static bool operator >=(Natural x, Natural y) { return CompareTo(x, y) >= 0; }
public static bool operator ==(Natural x, Natural y) { return CompareTo(x, y) == 0; }
public static bool operator !=(Natural x, Natural y) { return CompareTo(x, y) != 0; }
public override bool Equals(object obj) { return CompareTo(this, obj as Natural) == 0; }
public bool Equals(Natural x) { return CompareTo(this, x) == 0; }

private static int CompareTo(Natural x, Natural y) { ... }

关于c# - 应该是 IEquatable<T >'s Equals() be implemented via IComparable<T>' s CompareTo()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30276404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com