【发布时间】: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<Employee>而不是ArrayList,那么您当前的比较器工作正常。
标签: c#