我想比較對象的多個屬性,但我的代碼只能比較度數屬性。在Visual Studio中調試時,看起來我的代碼完全缺少else語句。我會很感激任何提示。IComparable CompareTo(),如何比較多個對象屬性?
class Student : IComparable
{
private string fName;
private string lName;
private string deg;
private int gra;
public Student(string firstName, string lastName, string degree, int grade)
{
fName = firstName;
lName = lastName;
deg = degree;
gra = grade;
}
public override string ToString()
{
string var = lName + ", " + fName + " (" + deg + ") Grade: " + gra;
return var;
}
public int CompareTo(object obj)
{
Student newStudent = obj as Student;
if (this.deg.CompareTo(newStudent.deg) == 1)
{
return 1;
}
else if (this.deg.CompareTo(newStudent.deg) != 1)
{
return -1;
}
else //this is what my code is ignoring and not ordering by firstname as well
{
if (this.fName == newStudent.fName)
{
return 0;
}
else if (this.fName != newStudent.fName)
{
return -1;
}
else
{
return 0;
}
}
}
}
您返回1,如果馬上度是相等的。這可能不是你想要的。 – 2017-10-14 06:37:18