实现IComparable

Nic*_*ick -2 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");
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

}

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


    }
Run Code Online (Sandbox Code Playgroud)

Dav*_*d M 11

你的路线:

array.Add(p1.Age = 6)
Run Code Online (Sandbox Code Playgroud)

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


Mar*_*dle 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);
  }
}
Run Code Online (Sandbox Code Playgroud)