/*C#中通过实现IComparable接口对对象数组进行排序*/
using System;
class Student:IComparable
{
private string _name;
private int _age;
public Student(string name,int age)
{
_name = name;
_age = age;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
public int CompareTo(object right)
{
if(!(right is Student))
{
throw new ArgumentException("参数必须为Student类型");
}
return _name.CompareTo(((Student)right)._name);
}
public override string ToString()
{
return _name;
}
}
class Test
{
static void Main()
{
Student[] arr = new Student[5];
arr[0] = new Student("张三",5);
arr[1] = new Student("李四",3);
arr[2] = new Student("王五",2);
arr[3] = new Student("马六",4);
arr[4] = new Student("钱七",1);
Array.Sort(arr);
foreach(Student i in arr)
{
Console.WriteLine(i + " " + i.Age);
}
}
}
C#中通过实现IComparable接口对对象数组进行排序
最新推荐文章于 2024-02-24 15:55:19 发布