IComparable 接口的秒用?(排序)
今天发现了一个新的排序方法,很简单实用!仅供参考:可以对任何类型的值进行排序。
using System;
using System.Collections.Generic;
using System.Text;
namespace 按类排序_接口_
{
class Program
{
static void Main(string[] args)
{
Student []arr=new Student [5];
arr[0] = new Student("张三",53);
arr[1] = new Student("李四", 35);
arr[2] = new Student("王五", 45);
arr[3] = new Student("马六", 55);
arr[4] = new Student("钱七", 53);
Array.Sort(arr);
foreach (Student i in arr )
{
Console.WriteLine(i); //ToString方法再此处调用
}
Console.Read();
}
}
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 _(((Student )right )._name );
}
/// <summary>
/// 重载ToString方法
/// </summary>
/// <returns></returns>
public override string ToString()
{
return _name;
}
}
}
打印效果: