在制作可比类时遇到问题

最后发布: 2014-04-04 08:52:34


问题

这是我在这里的第一篇文章。 我在尝试上类似的课程时遇到了问题,希望您能帮助我。

错误:

错误1'OutputMasterLibrary.Student'未实现接口成员'System.Collections.Generic.IComparer.Compare(OutputMasterLibrary.Student,OutputMasterLibrary.Student)''

我的代码:

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

namespace OutputMasterLibrary 
{
    public class Student : IComparable, IComparable<Student>
    {
        string name { get; set; }
        int age { get; set; }
        int studentNumber { get; set; }


        public Student(string myName, int myAge, int myNumber)
        {
            name = myName;
            age = myAge;
            studentNumber = myNumber;
        }


        public override bool Equals(object obj)
        {
            Student other = obj as Student;
            if (other == null)
            {
                return false;
            }
            return (this.name == other.name) && (this.studentNumber == other.studentNumber) && (this.age == other.age);
        }


        public override int GetHashCode()
        {
            return name.GetHashCode() + studentNumber.GetHashCode() + age.GetHashCode();
        }
    }
}
c# icomparable
回答

错误消息恰好说明了您所缺少的内容。

Student课堂上实施

public int Compare(Student student1, Student student2)


回答

public override bool Equals(Student x, Student y)
    {
        if (x == null || y == null)
        {
            return false;
        }
        if (x.Equals(y)) return true;
        return (x.name == y.name) && (x.studentNumber == y.studentNumber) && (y.age == y.age);
    }


回答

您已经实现了IComparableIcomparable<T> 因此,您必须实现这两个CompareTo方法。

    public int CompareTo(object obj) // implement method from IComaparable<T> interface
    {
        return CompareStudent(this, (Student)obj);
    }

    public int CompareTo(Student obj) // implement method from IComaparable interface
    {
        if (obj != null && !(obj is Student))
            throw new ArgumentException("Object must be of type Student.");
        return CompareStudent(this, obj);
    }

    public int CompareStudent(Student st1, Student st2)
    {
        // You can change it as you want
        // I am comparing their ages 
        return st1.age.CompareTo(st2.age);
    }