【问题标题】:Using Compare() method of the IComparer Interface使用 IComparer 接口的 Compare() 方法
【发布时间】:2017-06-19 01:00:37
【问题描述】:

谁能指出我的代码中的错误。 我想在 c# 中显示 IComparer 接口的“Compare()”的功能。 以下是我正在尝试使用的 2 个课程。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DayFive
{
    class Employee
{
    public int id;
    public String name;

    public Employee(int _id,String _name)
    {
        id = _id;
        name = _name;
    }

    static void Main(string[] args)
    {
        Employee e1 = new Employee(1, "Rishabh");
        Employee e2 = new Employee(2, "Shubham");
        Employee e3 = new Employee(3, "Akshay");

        ArrayList al=new ArrayList();
        al.Add(e1);
        al.Add(e2);
        al.Add(e3);

        //default
        al.Sort();

        IComparer<Employee> c = new MyCompare();
        al.Sort(c);
    }
}
}

和,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DayFive
{
class MyCompare : IComparer<Employee>
{
    public int Compare(Employee a,Employee b)
    {
        if (a.name.CompareTo(b.name) < 0)
            return -1;
        if (a.name.Equals(b.name))
            return 0;
        return 1;
    }


}
}

当 MyComparer 类的对象作为参数传入时,使用 arrayList 的 Sort() 时出现错误。

错误如下..

错误 1 ​​'System.Collections.ArrayList.Sort(System.Collections.IComparer)' 的最佳重载方法匹配有一些无效参数 c:\users\rkash4\documents\visual studio 2013\Projects\DayFive \DayFive\Program.cs 39 13 DayFive

错误 2 参数 1:无法从 'System.Collections.Generic.IComparer' 转换为 'System.Collections.IComparer' c:\users\rkash4\documents\visual studio 2013\Projects\DayFive\DayFive\ Program.cs 39 21 DayFive

【问题讨论】:

  • 愿意分享错误的实际含义吗?
  • ArrayList 不是通用的,所以你只需要一个IComparer。如果您使用List&lt;Employee&gt; 而不是ArrayList,那么您当前的比较器工作正常。

标签: c#


【解决方案1】:

ArrayList 不是通用的,所以你只需要一个IComparer。如果您使用List&lt;Employee&gt; 而不是ArrayList,那么您当前的比较器工作正常。

试试这个:

    Employee e1 = new Employee(1, "Rishabh");
    Employee e2 = new Employee(2, "Shubham");
    Employee e3 = new Employee(3, "Akshay");

    List<Employee> al = new List<Employee>();
    al.Add(e1);
    al.Add(e2);
    al.Add(e3);

    IComparer<Employee> c = new MyCompare();
    al.Sort(c);

无论如何你都应该使用ArrayList - 现在是2001年了。

【讨论】:

  • 谢谢,这很好地消除了错误。但是,它显示以下异常.. mscorlib.dll 中发生“System.InvalidOperationException”类型的未处理异常附加信息:无法比较数组中的两个元素
  • @iamrkcheers - 默认排序现在不起作用。把它拿出来。否则你的班级Employee 需要实现IComparable
  • 非常感谢 .. 完成了这项工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
相关资源
最近更新 更多