我的应用程序中有几个课程,所有这些都有 Name 我想用作比较基础的财产(Distinct(), , ETC。)。因为我总是会比较 Name, ,我决定提取一个接口, ISomeComparedStuff, ,只有一个 Name 建议我所有其他类实施的其他类别。我设置了一个比较类:

public class MyComparer : IEqualityComparer<ISomeComparedStuff>
{
     public bool Equals(ISomeComparedStuff x, ISomeComparedStuff y)
     {
          return x.Name == y.Name;
     }

     public int GetHashCode(ISomeComparedStuff obj)
     {
          return obj.Name.GetHashCode();
     }
}

唯一的问题是当我尝试对抗它时:

public class SomeStuff : ISomeComparedStuff
{
  ...
}

public class SomeMoreStuff : ISomeComparedStuff
{
  ...
}

var someStuff = GetSomeStuff().Distinct(new MyComparer);
var someMoreStuff = GetSomeMoreStuff().Distinct(new MyComparer);

我遇到了一个错误(SomeStuffISomeComparedStuff)。有什么方法可以做到这 Name)?

注意:我理解这个问题“标题”需要帮助。任何建议都很棒。

有帮助吗?

解决方案

不确定这是否是一个好的解决方案,但是如何使MyComparer成为通用类?

public class MyComparer<T> : IEqualityComparer<T>
    where T: ISomeComparedStuff
{
     public bool Equals(T x, T y)
     {
      return x.Name == y.Name;
     }

     public int GetHashCode(T obj)
     {
      return obj.Name.GetHashCode();
     }
}

不利的是您必须新的适当版本:

var someStuff = GetSomeStuff().Distinct(new MyComparer<SomeStuff>());
var someMoreStuff = GetSomeMoreStuff().Distinct(new MyComparer<SomeMoreStuff>());

稍微扩展,您还可以做出这样的新扩展方法:

public static IEnumerable<T> DistinctByName<T>(this IEnumerable<T> values)
    where T: ISomeComparedStuff
{
    return values.Distinct(new MyComparer<T>());
}

其他提示

也许类似:

var someStuff = GetSomeStuff().Cast<ISomeComparedStuff>().Distinct(new MyComparer);

或使用非生成 IEqualityComparer.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top