c# - 当 T 可以是 IEnumerable<T> 时实现 IEquatable<T>

标签 c# implementation structural-equality

我读过各种与我的问题类似的问题,但似乎没有一个能解决我的问题。

我有这样的类型:

class MyObject<T> : IEquatable<MyObject<T>> { // no generic constraints
  private readonly string otherProp;
  private readonly T value;

  public MyObject(string otherProp, T value)
  {
    this.otherProp = otherProp;
    this.value = value;
  }

  public string OtherProp { get { return this.otherProp; } }

  public T Value { get { return this.value; } }

  // ...

  public bool Equals(MyObject<T> other)
  {
    if (other == null)
    {
       return false;
    }

    return this.OtherProp.Equals(other.OtherProp) && this.Value.Equals(other.Value);
  }
}

T是一个标量 MyObject<int>平等工作正常,但当我定义了一些东西 喜欢MyObject<IEnumerable<int>>平等失败。

原因是当T为IEnumerable<T>时我应该调用this.Value.SequenceEqual(other.Value) .

处理这种差异膨胀 Equals(MyObject<T>)类型检查和反射的 LOC 太多(对我来说,导致违反 SOLID/SRP)。

我无法在 MSDN 指南中找到这个具体案例,所以如果有人已经遇到过这个问题;如果可以共享这些知识,那就太好了。

编辑:替代

对于 K.I.S.S.,我想做类似的事情:

class MyObject<T> : IEquatable<MyObject<T>> {
  private readonly IEnumerable<T> value;

  // remainder omitted
}

这样执行Equal会简单很多。当我只需要一个值时,我有一个包含 1 个项目的集合。 显然 T 不会是可枚举的(但数据结构是私有(private)的,所以没有问题)。

最佳答案

如果 TIEnumerable<T> ,您的代码比较了 IEnumerable<T> 的两个引用当然,这些引用可能不相等。实际上,当 T 是任何引用类型而不被重写 Equals 时,您会得到这种行为。方法。

如果你不想在这里比较引用,你应该写一个代码,它会根据内容比较这些序列。但是,您应该注意,该序列可能是无止境的。

关于c# - 当 T 可以是 IEnumerable<T> 时实现 IEquatable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15494518/

相关文章:

c# - 在 Internet Explorer 中使用 javascript 和 XPATH 获取元素

java - 棋盘游戏在 Java 中的实现

c# - Chris Lomont 的 C# FFT - 它是如何工作的

F# 记录结构比较排序

f# - F#中的结构相等

c# - Parent - C# 中的 CChild 管理

c# - Xamarin 表格 : ContentPages in TabbedPage

c# - 如何为自定义 map 类实现具有内联初始化的构造函数?

java - java中的多重排序