当T可以是IEnumerable <T>时,实现IEquatable <T>

jay*_*jay 6 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

什么时候T是标量,因为MyObject<int>平等正常,但是当我定义像MyObject<IEnumerable<int>>平等失败时.

原因是当IEnumerable<T>我是T时我应该打电话this.Value.SequenceEqual(other.Value).

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

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

编辑:替代方案

对于KISS,我想知道做类似的事情:

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

  // remainder omitted
}
Run Code Online (Sandbox Code Playgroud)

这样实现起来Equal会很简单.当我只需要一个值时,我就收集了1个项目.显然T不是可枚举的(但数据结构是私有的,所以没有问题).

Lee*_*Lee 3

您可以MyObject<T>为您的类型选择一个相等比较器T并使用它:

class MyObject<T> : IEquatable<MyObject<T>>
{
    private readonly IEqualityComparer<T> comparer;
    public MyObject(string otherProp, T value, IEqualityComparer<T> comparer)
    {
        this.comparer = comparer;
    }
    public MyObject(string otherProp, T value)
        : this(otherProp, value, EqualityComparer<T>.Default)
    {
    }

    public bool Equals(MyObject<T> other)
    {
        return OtherProp.Equals(other.OtherProp) && comparer.Equals(this.Value, other.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,IEnumerable<T>您可以使用比较器来比较序列而不是引用。您可能希望使用工厂方法来创建对象,以确保相同的比较器类型用于相同的对象,T以确保相等保持对称。