我正在尝试比较对象的多个属性,但我的代码只能比较程度属性。在 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;
}
}
}
}
首先回答你的问题(为什么else
部分永远不会被执行)已经得到回答,也就是说,条件的第三种可能性是1
or not 1
.
如果您尝试按不同的属性排序,例如,如果我们首先要按程度排序,然后按fName
那么我们可以实现 IComparer-
class Student : IComparer<Student>{
/*
codes
*/
public int Compare(Student student1, Student student2)
{
if(student1.deg.Equals(student2.deg)) //if both degrees are same
{
return string.Compare(student1.fName , student2.fName); // then compare fName
}
else
return string.Compare(student1.deg , student2.deg);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)