对类库的学习--IComparer

最近无聊翻了翻MSDN中的.NET  Framework SDK文档,随便看了看那些类库,看来看去很多空间下的接口好像重来没主动用过,于是了就找了一个接口System.Collections.IComparer学习学习,留下笔记,加深一下印象。

 

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ArrayList list = new ArrayList();
            for (int i = 1; i < 10; i++)
            {
                Person person = new Person(i);
                list.Add(person);
            }
            foreach (Person person in list)
            {
                Response.Write(person.Value+"<br/>");
            }

            System.Collections.IComparer myComparer = new PersonComparer();
            //使用指定的比较器对整个 ArrayList 中的元素进行排序

            list.Sort(myComparer);
            Response.Write("After sorting.....................<br/>");
            foreach (Person personTmp in list)
            {
                Response.Write(person.Value+"<br/>");
            }

        }
    }
    public class PersonComparer : System.Collections.IComparer
    {

        public int Compare(object x, object y)
        {
            Person personX = x as Person;
            if (personX == null)
            {
                throw new ArgumentException("Error", "x");
            }
            Person personY = y as Person;
            if (personY == null)
            {
                throw new ArgumentException("Error", "y");
            }
            Int32 xy = personX.Value.CompareTo(personY.Value);
            return -xy;//降序

            //return xy 升序
        }

    }

    public class Person
    {

       public Person(int i)
        {
            this._value= i;
        }

        private int _value;
        public int Value
        {
            get
            {
                return _value;
            }
            set
            {
                _value= value;
            }
        }
    }

posted on 2009-01-05 15:29  张林春  阅读(272)  评论(0编辑  收藏  举报