题目说明:学生类包括成绩、科目和学号,请根据课程成绩grade将学生进行排序。
public class Student : IComparable
{
public double mygrade;
public string mysubject, myID;
public Student() { }
public Student(double grade, string subject, string id)
{
mygrade = grade;
mysubject = subject;
myID = id;
}
if (!(obj is Student))
throw new ArgumentException("Object is not a Student");
Student otherStudent = (Student)obj;
if (mygrade > otherStudent.mygrade)
return 1;
else if (mygrade < otherStudent.mygrade)
return -1;
else
return 0;}
internal class Program
{
private static void Main(string[] args)
{
Student[] students = new Student[5];
students[0] = new Student(50.0, "windows程序设计", "001");
students[1] = new Student(90.0, "windows程序设计", "002");
students[2] = new Student(100.0, "windows程序设计", "003");
students[3] = new Student(70.0, "windows程序设计", "004");
students[4] = new Student(80.0, "windows程序设计", "005");
Array.Sort(students);
Console.WriteLine(students[1].mygrade);
}
}
开始改写提示
public int CompareTo(object obj)
{
return mygrade.CompareTo(obj);
}
没有细想爆出类型不匹配的错误,发现将double和obj类型匹配,尝试将object 改为我所需要的 Student类型,结果报错了,提示我没有改写方法,应该用中间变量转换
以下是借助工具给出的解答
这种写法是有问题的,因为CompareTo方法中的参数obj是一个Object类型的对象,而mygrade是一个double类型的值。在此方法中,您将使用mygrade对象调用CompareTo方法,将obj作为参数传递,这会导致类型不匹配的异常。
正确的做法是将传递给CompareTo方法的obj参数转换为Student类型,然后再比较其mygrade属性。此外,您应该检查obj参数是否为null,并在其不是Student对象时,抛出ArgumentException异常。
以下是一个更好的实现方式:
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (obj is Student otherStudent)
return mygrade.CompareTo(otherStudent.mygrade);
else
throw new [ArgumentException](poe://www.poe.com/_api/key_phrase?phrase=ArgumentException&prompt=Tell%20me%20more%20about%20ArgumentException.)("Object is not a Student");
}