2009-12-12 65 views
-2

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

可比:

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


    } 
+0

顺便说一句:如果你在NET 3.5的,你不需要使用排序()和IComparable。有一个名为OrderBy的新扩展方法比Sort更容易使用。 – 2009-12-12 19:11:41

+4

如果他在.net 3.5(或2.0)上,他真的不应该使用ArrayList,而是列出。他不会有这个问题,如果他这样做(他会得到一个编译错误,并可能会找出问题)。 – 2009-12-12 19:14:42

+0

为什么不使用通用'List '和'IComparable '? – thecoop 2009-12-12 19:15:11

回答

11

你行:

array.Add(p1.Age = 6) 

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

+0

粗糙...谢谢 – Nick 2009-12-12 19:22:54

1

您正在将person.Age添加到您的数组列表中,并且person.Age是一个int。
你应该这样做

Person p1 = new Person(){Age=3}; 
array.Add(p1); 
4

你不添加人到阵列。

p1.Age = 6 

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

您需要在将人员放入数组之前完成赋值。

如果您只是希望将单一类型的元素放入集合中,则希望使用类型化集合而不是非类型集合。这会立即发现问题。

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); 
    } 
} 
+0

你可能想添加if(other == null)return 1;在您的CompareTo – mayu 2011-07-05 09:15:47

+0

@Tymek中,好处是,此实现不会优雅地处理其他类型的对象(异构集合),甚至不会有相同类型的空值。 – Constantin 2011-07-15 07:24:12

相关问题