我正在尝试比较对象的多个属性,但我的代码只能比较度属性。在Visual Studio中进行调试时,似乎我的代码完全缺少else语句。我会很感激任何提示。
//define model
$scope.tobeDeleted = {}; //then place deleted property here
//you could easily access `$scope.tobeDeleted.deletedId` inside a controller
答案 0 :(得分:1)
您的问题的第一个答案(为什么else
部分永远不会被执行)已经得到回答,也就是说,没有第三种情况可能是1
或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);
}
}
答案 1 :(得分:0)
在您的代码中
if (this.deg.CompareTo(newStudent.deg) == 1)
{
// do something
}
else if (this.deg.CompareTo(newStudent.deg) != 1)
{
// do something
}
else
{
// do something
}
永远不会达到else语句,因为结果可以等于1。 而且你只检查'deg'值。例如,您可以检查它们是否相同:
public int CompareTo(object obj)
{
if (obj == null)
{
return -1;
}
Student newStudent = obj as Student;
// are equal
if (deg.CompareTo(newStudent.deg) == 0 &&
gra.CompareTo(newStudent.gra) == 0 &&
lName.CompareTo(newStudent.lName) == 0 &&
fName.CompareTo(newStudent.fName) == 0)
{
return 0;
}
else
{
return 1;
}
}
答案 2 :(得分:0)
如果this.deg.CompareTo(newStudent.deg) == 1
则返回1,如果this.deg.CompareTo(newStudent.deg) != 1
则返回-1。由于比较要么是,要么等于1,你永远不会到达其余的。
因此,您的代码应如下所示:
partial class Student : IComparable, IComparable<Student>
{
public int CompareTo(object obj)
{
if (obj != null && obj.GetType() != GetType())
{
// From https://msdn.microsoft.com/en-us/library/system.icomparable.compareto(v=vs.110).aspx#Remarks
// The parameter, obj, must be the same type as the class or value type that implements this interface; otherwise, an ArgumentException is thrown.
throw new ArgumentException(string.Format("Object must be of type {0}", GetType()));
}
return CompareTo((Student)obj);
}
public int CompareTo(Student newStudent)
{
if (object.ReferenceEquals(this, newStudent))
return 0;
else if (newStudent == null)
// From https://msdn.microsoft.com/en-us/library/43hc6wht(v=vs.110).aspx#Remarks
// By definition, any object compares greater than null, and two null references compare equal to each other.
return 1;
var cmp = this.deg.CompareTo(newStudent.deg);
if (cmp != 0)
return cmp;
cmp = this.fName.CompareTo(newStudent.fName);
if (cmp != 0)
return cmp;
// Compare additional members as required, return the first nonzero member comparison.
// Finally return 0 if all member comparisons returned 0.
return 0;
}
}
注意:
如果您要实施IComparable
,您还应该IComparable<Student>
中解释的原因实施IComparable
and IComparable<T>
。
由于IComparable
是由可以排序或排序的类型实现,如IComparable<T>.CompareTo
Method (T): Notes to Implementers所述,您应确保您的比较方法为{{3} }。通过连续调用CompareTo
成员的Student
方法,并返回第一个非零值,您可以确保是这种情况。