【发布时间】:2017-10-14 06:35:40
【问题描述】:
我正在尝试比较对象的多个属性,但我的代码只能比较 degree 属性。在 Visual Studio 中调试时,我的代码似乎完全缺少 else 语句。如果有任何提示,我将不胜感激。
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。这可能不是你想要的。
标签: c#