何时使用 IComparable对比。 IComparer

发布于 2024-07-13 22:12:07 字数 60 浏览 11 评论 0原文

我正在尝试找出我需要实现哪些接口。 他们本质上都做同样的事情。 我什么时候会使用其中一种而不是另一种?

I'm trying to figure out which of these interfaces I need to implement. They both essentially do the same thing. When would I use one over the other?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

寻找我们的幸福 2024-07-20 22:12:07

它们并不完全一样,因为 IComparer 是在能够比较两个不同对象的类型上实现的,而 IComparable 是在能够比较两个不同对象的类型上实现的。 code> 是在能够将自身与相同类型的其他实例进行比较的类型上实现的。

当我需要知道另一个实例如何与 this 实例相关时,我倾向于使用 IComparableIComparer 对于对集合进行排序非常有用,因为 IComparer 位于比较之外。

Well they are not quite the same thing as IComparer<T> is implemented on a type that is capable of comparing two different objects while IComparable<T> is implemented on types that are able to compare themselves with other instances of the same type.

I tend to use IComparable<T> for times when I need to know how another instance relates to this instance. IComparer<T> is useful for sorting collections as the IComparer<T> stands outside of the comparison.

北笙凉宸 2024-07-20 22:12:07

当类具有内部比较时,请使用 IComparable

当您需要除类的内部比较(如果有)之外的比较方法时,请使用 IComparer

Use IComparable<T> when the class has an intrinsic comparison.

Use IComparer<T> when you want a comparison method other than the class' intrinsic comparison, if it has one.

翻了热茶 2024-07-20 22:12:07

这取决于实体。 例如,对于像“Student”这样的类,基于名称使用 IComparable 是有意义的。

class Student : IComparable 
{
    public string Name { get; set; }
    public int MathScore { get; set; }
    public int EnglishScore { get; set; }

    public int TotalScore 
    {
        get
        {
            return this.MathScore + this.EnglishScore; 
        }
    }

    public int CompareTo(object obj)
    {
        return CompareTo(obj as Student);  
    }

    public int CompareTo(Student other)
    {
        if (other == null)
        {
            return 1;
        }
        return this.Name.CompareTo(other.Name);  
    }
}

但是,如果老师“A”想根据 MathScore 比较学生,而老师“B”想根据 EnglishScore 比较学生。 单独实现 IComparer 是个好主意。 (更像是一种策略模式)

class CompareByMathScore : IComparer<Student>
{
    public int Compare(Student x, Student y)
    {
        if (x.MathScore > y.MathScore)
          return 1;
        if (x.MathScore < y.MathScore)
          return -1;
        else
          return 0;
    }
}

It depends on the entity. For example following for a class like "Student", it will make sense to have IComparable based on Name.

class Student : IComparable 
{
    public string Name { get; set; }
    public int MathScore { get; set; }
    public int EnglishScore { get; set; }

    public int TotalScore 
    {
        get
        {
            return this.MathScore + this.EnglishScore; 
        }
    }

    public int CompareTo(object obj)
    {
        return CompareTo(obj as Student);  
    }

    public int CompareTo(Student other)
    {
        if (other == null)
        {
            return 1;
        }
        return this.Name.CompareTo(other.Name);  
    }
}

But if a teacher 'A' wants to compare students based on MathScore, and teacher 'B' wants to compare students based on EnglishScore. It will be good idea to implement IComparer separately. (More like a strategy pattern)

class CompareByMathScore : IComparer<Student>
{
    public int Compare(Student x, Student y)
    {
        if (x.MathScore > y.MathScore)
          return 1;
        if (x.MathScore < y.MathScore)
          return -1;
        else
          return 0;
    }
}
蓝天白云 2024-07-20 22:12:07

通过故事进行简单解释

高中篮球。 这是球队选择的校园。 我想招募团队中最高/最好/最快的人。 我该怎么办?

IComparer Interface - 比较两个人单独的人

  • 这使我可以比较任何两个排队的人......基本上就是这样。 Fred vs John......我把它们放入一个实现接口的具体类中。 Compare(Fred, John) 它会指出谁更好。

IComparable 怎么样? - 将自己与其他人进行比较

您最近上过 FB 吗? 您会看到其他人在做很酷的事情:环游世界、创造发明,而我正在做一些不太酷的事情 - 我们正在做的是利用 IComparable 接口。

  • 我们正在将当前实例(您自己)与同一类型(人)的另一个对象(其他人)进行比较。

Comparer 类怎么样?

Comparer 类是一个实现 IComparer 接口的抽象基类。 您应该从此类派生以获得具体的实现。 无论如何,微软建议您使用 Comparer 类而不是实现 IComparer 接口:

我们建议您从 Comparer 类派生而不是实现 IComparer 接口,因为 Comparer 类提供了 IComparer.Compare 方法的显式接口实现以及用于获取对象的默认比较器的 Default 属性。

总结

  • IComparer - 将两个事物排列起来并进行比较。
  • IComparable - 将自己与 FB 上的其他人进行比较。

希望这些故事能帮助你记住。

Simple Explanation via a story

High school basketball. It's a school yard pick for the teams. I want to get the tallest/best/fastest folks on my team. What do I do?

IComparer Interface - Compare two people separate people

  • This allows me to compare any two guys lined up.........that's basically it. Fred vs John..........i throw them into a concrete class which implements the interface. Compare(Fred, John) and it spits out who's better.

What about IComparable? - Compare yourself with someone else

Have you been on FB recently? You see other folks doing cool things: travelling the world, creating inventions, while I'm doing something not quite as cool - well what we are doing is making use of the IComparable interface.

  • We are comparing the current instance (yourself) with another object (someone else) which is of the same type (person).

What about the Comparer Class?

The Comparer class is an abstract base class which implements the IComparer interface. You should derive from this class to have a concrete implementation. anyways, Microsoft recommends that you DO use the Comparer class rather than implement the IComparer interface:

We recommend that you derive from the Comparer class instead of implementing the IComparer interface, because the Comparer class provides an explicit interface implementation of the IComparer.Compare method and the Default property that gets the default comparer for the object.

Summary

  • IComparer - line up two things and compare.
  • IComparable - compare yourself with others on FB.

Hope the stories help you remember.

夏の忆 2024-07-20 22:12:07

这完全取决于您的类型是否可变。 您应该在非可变类型上实现 IComparable。 请注意,如果实现 IComparable,则必须重写 Equals 以及 ==、!=、< 和> 运算符(请参阅代码分析警告 CA1036)。

引用 这篇博文中的 Dave G 的话:

但是,如果您的对象是可变的,正确的答案是实现 IComparer 而不是 IComparable,并在必要时将 IComparer 的实例传递给排序函数。

由于 IComparer 只是用于在该时间点进行排序的一次性对象,因此您的对象可以具有您想要的任何可变语义。 此外,它不要求甚至不建议使用 Equals、GetHashCode 或 == - 您可以随意以任何您喜欢的方式定义它。

最后,您可以为您的类型定义多个 IComparer,以便根据不同字段或使用不同规则进行排序。 这比拘泥于一种定义要灵活得多。

简而言之: 对值类型使用 IComparable,对引用类型使用 IComparer。

It all depends on whether your type is mutable or not. You should only implement IComparable on non-mutable types. Note that if you implement IComparable, you must override Equals, along with the ==, !=, < and > operators (see Code Analysis warning CA1036).

Quoting Dave G from this blog post:

But the correct answer is to implement IComparer instead of IComparable if your objects are mutable, and pass an instance of the IComparer to sorting functions when necessary.

Since the IComparer is just a disposable object used for sorting at that point in time, your object can have any mutable semantics you desire. Furthermore, it doesn't require or even suggest using Equals, GetHashCode, or == - you're free to define it in any way you please.

Finally, you can define multiple IComparer's for your type for sorting on different fields or with different rules. This is much more flexible than being stuck with one definition.

In short: Use IComparable for value types and IComparer for reference types.

离鸿 2024-07-20 22:12:07

正如其他人所说,他们不做同样的事情。

无论如何,这些天我倾向于不使用 IComparer。 我为什么要? 它的职责(用于比较两个对象的外部实体)可以使用 lambda 表达式更清晰地处理,类似于大多数 LINQ 方法的工作方式。 编写一个快速 lambda,它将要比较的对象作为参数,并返回一个 bool。 如果对象定义了自己的内部比较操作,则它可以实现 IComparable。

As others have said, they don't do the same thing.

In any case, these days I tend not to use IComparer. Why would I? Its responsibility (an external entity used to compare two objects) can be handled much cleaner with a lambda expression, similar to how most of LINQ's methods work. Write a quick lambda which takes the objects to compare as arguments, and returns a bool. And if the object defines its own intrinsic compare operation, it can implement IComparable instead.

旧情勿念 2024-07-20 22:12:07

IComparer 是一个用于对数组进行排序的接口,该接口将强制该类实现
Compare(T x,T y) 方法,它将比较两个对象。 实现该接口的类的实例用于数组的排序。

IComparable 是在需要比较同一类型的两个对象的类型中实现的接口,这个可比较接口将强制该类实现以下方法 CompareTo(T obj)

IEqualityComparer 是一个接口,用于查找对象是否无论是否相等,现在我们将在示例中看到这一点,我们必须在集合中找到对象的不同之处。 该接口将实现一个方法
Equals(T obj1,T obj2)

现在我们举一个例子,我们有一个 Employee 类,基于这个类我们必须创建一个 Collection。 现在我们有以下要求。

使用 Array 类对数组进行排序
2. 需要使用 Linq 的集合:删除重复项、按从高到低排序、删除一个员工 ID

abstract public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { set; get; }
}

public enum SortType
{
    ByID,
    BySalary
}

public class EmployeeIdSorter : IComparer
{
公共 int 比较(员工 x,员工 y)
{
if (x.Id < y.Id)
返回1;
否则如果 (x.Id > y.Id)
返回-1;
别的
返回0;
}
下面

    public class EmployeeSalarySorter : IComparer<Employee>
    {
        public int Compare(Employee x, Employee y)
        {
            if (x.Salary < y.Salary)
                return 1;
            else if (x.Salary > y.Salary)
                return -1;
            else
                return 0;
        }
    }

有关更多信息,请参阅
http://dotnetvisio.blogspot.in/2015/12 /usage-of-icomparer-icomparable-and.html

IComparer is a interface which is used to sort the Array, this interface will force the class to implement the
Compare(T x,T y) method, which will compare the two objects. The instance of the class which implemented this interface is used in the sorting of the Array.

IComparable is a interface is implemented in the type which needs to compare the two objects of the same type, This comparable interface will force the class to implement the following method CompareTo(T obj)

IEqualityComparer is a interface which is used to find the object whether it is Equal or not, Now we will see this in a sample where we have to find the Distinct of a Object in a collection. This interface will implement a method
Equals(T obj1,T obj2)

Now we take a Example we have a Employee class , based on this class we have to create a Collection. Now we have the following requirements.

Sort the Array using Array class
2. Need an collection using Linq : Remove the Duplicate, Order by higher to lower, Remove one employee id

abstract public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { set; get; }
}

public enum SortType
{
    ByID,
    BySalary
}

public class EmployeeIdSorter : IComparer
{
public int Compare(Employee x, Employee y)
{
if (x.Id < y.Id)
return 1;
else if (x.Id > y.Id)
return -1;
else
return 0;
}
}

    public class EmployeeSalarySorter : IComparer<Employee>
    {
        public int Compare(Employee x, Employee y)
        {
            if (x.Salary < y.Salary)
                return 1;
            else if (x.Salary > y.Salary)
                return -1;
            else
                return 0;
        }
    }

For more info refere below
http://dotnetvisio.blogspot.in/2015/12/usage-of-icomparer-icomparable-and.html

风和你 2024-07-20 22:12:07

IComparable 表示一个对象可以与另一个对象进行比较。
IComparer 是一个可以比较任意两个项目的对象。

IComparable says an object can be compared with another.
IComparer is an object that can compare any two items.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文