2009-12-12 52 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

相關問題