-2

我正在实施 IComparable 来对类型对象进行排序。我的问题是为什么它将类型 person 转换为 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

4 回答 4

11

您的线路:

array.Add(p1.Age = 6)

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

于 2009-12-12T19:11:25.030 回答
7

The best way to implement IComparable is to implement IComparable<T> and pass the calls on to that implementation:

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);
  }
}
于 2009-12-12T19:38:30.257 回答
4

您没有将 Persons 添加到数组中。

p1.Age = 6

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

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

If you're only looking to put elements of a single type into a collection, you want to use a typed collection rather than an untyped one. This would have caught the problem immediately.

于 2009-12-12T19:14:29.750 回答
1

您正在将 person.Age 添加到您的数组列表中,而 person.Age 是一个 int。
你应该做类似的事情

Person p1 = new Person(){Age=3};
array.Add(p1);
于 2009-12-12T19:13:22.817 回答