实现IComparable的 [英] Implementing IComparable

查看:182
本文介绍了实现IComparable的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我implmenting了IComparable排序喜欢类型的对象。我的问题是,为什么它铸铅字人INT32?该数组排序()似乎蒙上每种类型的数组,我用比较的类型



比较的:

 公共类人:IComparable的
{
保护INT年龄;

公众诠释年龄{搞定;组; }

公众诠释的CompareTo(obj对象)
{
如果(obj是人)
{
变种人=(人)OBJ;
返回age.CompareTo(person.age);
}
,否则
{
抛出新的ArgumentException(对象的类型的人不是);
}
}
}



}

 类节目
{
静态无效的主要(字串[] args)
{
的人P1 =新的Person();
的人P2 =新的Person();
的人P3 =新的Person();
的人P4 =新的Person();

ArrayList的数组=新的ArrayList();

array.Add(p1.Age = 6);
array.Add(p2.Age = 10);
array.Add(p3.Age = 5);
array.Add(p4.Age = 11);

的Array.Sort();

的foreach(数组列表VAR)
{
变种人=(人)名单; //转换异常这里。

Console.WriteLine(list.GetType()的ToString()); //返回System.Int32
}
到Console.ReadLine();


}


解决方案

您行:

  array.Add(p1.Age = 6)

添加语句 p1.Age = 6 到ArrayList的结果。这是int值6.没事做IComparable的排序或


I am implmenting the IComparable to sort like typed objects. My question is why does it cast type person to int32? The array's Sort() seems to cast each type in the array to the type that I am using for comparison.

Comparable:

public class Person:IComparable 
{
   protected int age;

   public int Age { get; set; }

   public int CompareTo(object obj)
   {
       if(obj is Person)
       {
           var person = (Person) obj;
          return age.CompareTo(person.age);
       }
       else
       {
           throw new ArgumentException("Object is not of type Person");
       }
   }
}

}

class Program
{
    static void Main(string[] args)
    {
        Person p1 = new Person();
        Person p2 = new Person();
        Person p3 = new Person();
        Person p4 = new Person();

        ArrayList array = new ArrayList();

        array.Add(p1.Age = 6);
        array.Add(p2.Age = 10);
        array.Add(p3.Age = 5);
        array.Add(p4.Age = 11);

        array.Sort();

        foreach (var list in array)
        {
            var person = (Person) list; //Cast Exception here.

            Console.WriteLine(list.GetType().ToString()); //Returns System.Int32
        }
        Console.ReadLine();


    }

解决方案

Your line:

array.Add(p1.Age = 6)

adds the result of the statement p1.Age = 6 to the ArrayList. This is the int value 6. Nothing to do with IComparable or Sort.

这篇关于实现IComparable的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆