码迷,mamicode.com
首页 > 其他好文 > 详细

IComparable和IComparer

时间:2015-10-27 23:36:58      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace no._1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arr1 = new ArrayList() {
            new Person() { Name="Shi",Age=17 },
            new Person() { Name="Da",Age=21 },
            new Person() { Name="Wu",Age=14 }};

            Console.WriteLine("arr1 Before:");
            for (int i = 0; i < arr1.Count; i++)
            {
                Console.WriteLine(((Person)arr1[i]).Name);
            }

            arr1.Sort();
            Console.WriteLine("arr1 After Sort:");
            for (int i = 0; i < arr1.Count; i++)
            {
                Console.WriteLine(((Person)arr1[i]).Name);
            }

            ArrayList arr2 = new ArrayList() {
            new Person() { Name="K",Age=21 },
            new Person() { Name="D",Age=24 },
            new Person() { Name="W",Age=15 },
            new Person() { Name="Z",Age=25 } };

            Console.WriteLine("arr2 Before:");
            for (int i = 0; i < arr2.Count; i++)
            {
                Console.WriteLine(((Person)arr2[i]).Name);
            }

            arr2.Sort(new PersonByAge());
            Console.WriteLine("arr2 After Sort:");
            for (int i = 0; i < arr2.Count; i++)
            {
                Console.WriteLine(((Person)arr2[i]).Name);
            }

            Console.ReadKey();
        }

        class PersonByAge : IComparer
        {
            public int Compare(object x, object y)
            {
                Person p1 = x as Person;
                Person p2 = y as Person;

                if(p1!=null && p2!=null)
                {
                    return p1.Age - p2.Age;
                }
                else
                {
                    throw new ArgumentException() { };
                }
            }
        }

        class Person : IComparable
        {
            public string Name { get; set; }
            public int Age { get; set; }

            public int CompareTo(object obj)
            {
                Person p = obj as Person;
                if (p == null)
                {
                    throw new ArgumentException() { };
                }
                else
                {
                    return p.Age - this.Age;
                }
            }
        }
    }
}

 

IComparable和IComparer

标签:

原文地址:http://www.cnblogs.com/shiblog/p/4915895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!