c# 学习笔记 ArrayList的Sort方法的实现

<span style="font-size:18px;">class Person :IComparable</span>
<span style="font-size:18px;">{
        public int Age;
        public string Name;
        public Person(int age,string name)
        {
            this.Age = age;
            this.Name = name;
        }

        public int CompareTo(object obj)
        {
            if (obj is Person)
            {
                return this.Age - (obj as Person).Age;
            }
            else
            {
                throw new ArgumentException("type error");
            }
        }
}</span>
<span style="font-size:18px;">
</span>
<pre name="code" class="csharp"><span style="font-size:18px;">class ComparePerson:IComparer
{
        public static IComparer Default = new ComparePerson();
        int IComparer.Compare(object x, object y)
        {
            if ((x is Person) && (y is Person))
            {
                return Comparer.Default.Compare(((Person)x).Name, ((Person)y).Name);
            }
            else
            {
                throw new ArgumentException("typer error");
            }
        }
}</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">
</span>
<span style="font-size:14px;">class Program
    {
        static void Main(string[] args)
        {
            ArrayList Persons = new ArrayList();
            Persons.Add(new Person(30, "Jim"));
            Persons.Add(new Person(25, "Bob"));
            Persons.Add(new Person(27, "Bert"));
            Persons.Add(new Person(22, "Ernie"));
            for(int i=0;i<Persons.Count;i++)
            {
                Console.WriteLine("{0},({1})", ((Person)Persons[i]).Name, ((Person)Persons[i]).Age);

            }
            Console.WriteLine();
            Console.WriteLine("age:-----------------------");
            Persons.Sort();  默认的排序方式是调用了实现Icomparable接口的Person类中的CompareTo方法
            for (int i = 0; i < Persons.Count; i++)
            {
                Console.WriteLine("{0},({1})", ((Person)Persons[i]).Name, ((Person)Persons[i]).Age);

            }
            Console.WriteLine();
            Console.WriteLine("name:-----------------------");
            Persons.Sort(ComparePerson.Default);  /非默认排序使用了实现IComparer的ComparePerson类 类中有一个公共静态字段以方便使用public static IComparer Default = new ComparePerson();
            for (int i = 0; i < Persons.Count; i++)
            {
                Console.WriteLine("{0},({1})", ((Person)Persons[i]).Name, ((Person)Persons[i]).Age);

            }
            Console.ReadKey();
        }
    }</span>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值