interface IComparer Error方法没有过载'排序'需要2个参数

时间:2015-10-27 20:15:40

标签: c# interface

我应该在其他类中调用Interface的方法Sort,其中包括List 但我无法找到正确的解决方案,不过我的例子是我的老师。

错误:方法没有过载'排序'需要2个参数。

班级学生:人

 public class SortByName : IComparer
        {
            int IComparer.Compare(object obj1, object obj2)
            {
                Student st1 = (Student)obj1;
                Student st2 = (Student)obj2;
                return st1.Name.CompareTo(st2.Name);
            }
        }

class AcademyGroup:

    List<Student> group;    
    --------//---------
    public void Sort()
            {
                   group.Sort (group, new Student.SortByName());
            }

2 个答案:

答案 0 :(得分:0)

Sort来电的问题在于您尝试两次group - 一次作为.左侧调用的目标,再过一次方法的第一个参数。

接口的实现也存在问题:您应该实现通用版本。

这将解决问题:

using System.Collections.Generic;
...
public class SortByName : IComparer<Student> {
    public int Compare(Student st1, Student st2) {
        return st1.Name.CompareTo(st2.Name);
    }
}
...
group.Sort(new Student.SortByName());

请注意IComparer<T>System.Collections.Generic命名空间的成员,而您使用的IComparerSystem.Collections命名空间的成员。如果您还需要非泛型版本,则需要更改using指令或完全限定声明。

答案 1 :(得分:0)

List<T>.Sort采用通用IComparer<T>,而非非通用IComparer。让你的比较器通用:

    public class SortByName : IComparer<Student>
    {
        int IComparer.Compare(Student st1, Student st2)
        {
            return st1.Name.CompareTo(st2.Name);
        }
    }

此外,您不需要将group作为参数传递给group.Sort,只需通过比较器:

group.Sort (new Student.SortByName());