简体   繁体   English

在 C# 中的 IEqualityComparer 中使用泛型

[英]Using Generics in an IEqualityComparer in C#

I have a C# class defined like this:我有一个 C# 类定义如下:

public class Group<T> : ICloneable where T : CustomGroup
{
  ...
}

When I had originally implemented this, it was without generics.当我最初实现它时,它没有泛型。 However, due to some new requirements, I've had to utilize generics on this class.但是,由于一些新的要求,我不得不在这个类上使用泛型。 Now, this class had an IEqualityComparer .现在,这个类有一个IEqualityComparer It worked in it's pre-generics implementation.它在它的预泛型实现中起作用。 However, now, I'm not sure how to to define the class and method signatures.但是,现在,我不确定如何定义类和方法签名。

public class GroupComparer : IEqualityComparer<Group>
{
  public bool Equals(Group a, Group b)
  {
    return (a.Id == b.Id);
  }

  public int GetHashCode(Group obj)
  {
    return obj.GetHashCode();
  }
}

This no longer compiles saying "Using the generic type Group requires 1 type arguments".这不再编译说“使用泛型类型组需要 1 个类型参数”。 However, I'm not sure how to update the class and method signatures to support Group<T> where T has to be a CustomGroup .但是,我不确定如何更新类和方法签名以支持Group<T> ,其中 T 必须是CustomGroup

Is there a way to do this?有没有办法做到这一点? If so, how?如果是这样,如何?

Make your comparer-class generic as well:使您的比较器类也通用:

public class GroupComparer<T> : IEqualityComparer<Group<T>> where T : CustomGroup
{
  public bool Equals(Group<T> a, Group b<T>)
  {
    return (a.Id == b.Id);
  }

  public int GetHashCode(Group<T> obj)
  {
    return obj.GetHashCode();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM