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){……}呢?执行过程是怎么的呢?
{
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
第一个Name(红色),和第二个Name(绿色)分别是比较的左边和右边。
因此,Name并不特指stu[0]~stu[3]中的具体哪一个,而是进行两两比较时的参与者。