C#实现CompareTO()

.Net技术 码拜 8年前 (2016-03-05) 1324次浏览
 namespace Comp
{
class Student : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(object obj)
{
Student student = obj as Student;
return Name.CompareTo(student.Name);//怎么理解?
}
}
class Program
{
static void Main(string[] args)
{
Student[] stu = new Student[4];
stu[0] = new Student() { Age = 1, Name = “a1” };
stu[1] = new Student() { Age = 5, Name = “g1” };
stu[2] = new Student() { Age = 4, Name = “b1” };
stu[3] = new Student() { Age = 2, Name = “f1” };
Array.Sort(stu);
foreach (Student item in stu)
{
Console.WriteLine(“{0}–{1}”, item.Age, item.Name);
}
Console.ReadLine();
}
}
}
问一下代码中的Name.CompareTo(student.Name)怎么理解?这个Name指的是stu[0]~stu[3]中的哪一个?Main()中对stu初始化后,是不是已经执行了 public int CompareTo(object obj){……}呢?执行过程是怎么的呢?
解决方案

20

IComparable是Array.Sort的排序依据

20

引用 LZ twlyy 的回复:

问一下代码中的Name.CompareTo(student.Name)怎么理解?

第一个Name(红色),和第二个Name(绿色)分别是比较的左边和右边
因此,Name并不特指stu[0]~stu[3]中的具体哪一个,而是进行两两比较时的参与者。


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C#实现CompareTO()
喜欢 (0)
[1034331897@qq.com]
分享 (0)