简体   繁体   中英

Using Generics in an IEqualityComparer in C#

I have a C# class defined like this:

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 . 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". However, I'm not sure how to update the class and method signatures to support Group<T> where T has to be a 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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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