这是我在这里的第一篇文章。我在尝试上课时遇到了问题,我希望你能帮助我。
错误:
错误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();
}
}
}
答案 0 :(得分:2)
错误消息确切地说明了您缺少的内容。
在Student
班级
public int Compare(Student student1, Student student2)
答案 1 :(得分:1)
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);
}
答案 2 :(得分:1)
您已实施IComparable
和Icomparable<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);
}