我實踐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();
}
順便說一句:如果你在NET 3.5的,你不需要使用排序()和IComparable。有一個名爲OrderBy的新擴展方法比Sort更容易使用。 – 2009-12-12 19:11:41
如果他在.net 3.5(或2.0)上,他真的不應該使用ArrayList,而是列出。他不會有這個問題,如果他這樣做(他會得到一個編譯錯誤,並可能會找出問題)。 –
2009-12-12 19:14:42
爲什麼不使用通用'List'和'IComparable '? –
thecoop
2009-12-12 19:15:11