实现IComparable

时间:2009-12-12 19:09:07

标签: c# icomparable

我正在将IComparable归类为类似对象的排序。我的问题是为什么它将类型转换为int32?数组的Sort()似乎将数组中的每个类型转换为我用于比较的类型。

比较的:

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();


    }

4 个答案:

答案 0 :(得分:11)

你的专栏:

array.Add(p1.Age = 6)

将语句p1.Age = 6的结果添加到ArrayList。这是int值6.与IComparable或Sort无关。

答案 1 :(得分:7)

实施IComparable的最佳方法是实施IComparable<T>并将调用传递给该实现:

class Person : IComparable<Person>, IComparable
{
  public int Age { get; set; }

  public int CompareTo(Person other)
  {
    // Should be a null check here...
    return this.Age.CompareTo(other.Age);
  }

  public int CompareTo(object obj)
  {
    // Should be a null check here...
    var otherPerson = obj as Person;
    if (otherPerson == null) throw new ArgumentException("...");
    // Call the generic interface's implementation:
    return CompareTo(otherPerson);
  }
}

答案 2 :(得分:4)

您没有将人员添加到数组中。

p1.Age = 6

是一个赋值,它返回赋给变量/ property的任何内容(在本例中为6)。

在将人员放入数组之前,您需要进行分配。

如果您只想将单个类型的元素放入集合中,则需要使用类型化集合而不是非类型集合。这会立即解决问题。

答案 3 :(得分:1)

你正在添加person.Age到你的arraylist和person.Age是一个int 你应该做点什么

Person p1 = new Person(){Age=3};
array.Add(p1);
相关问题