我正在尝试学习排序数组的一些示例。示例使用 Id 作为整数来按此属性排序,因为我的对象使用 Guid 数据类型而不是 int 我决定使用 Created DateTime 属性对数组进行排序。这是代码
Car.cs
public class Car:ICar,IComparable
{
... properties
int IComparable.CompareTo(object)
{
Car temp = obj as Car;
if (temp != null)
{
if (this.Created > temp.Created)
return 1;
if (this.Created < temp.Created)
return -1;
else
return 0;
}
else {throw new ArgumentException("Parameter is not a Car object");}
}
}
车库.cs
public class Garage : IEnumerable
{
private Car[] cars = new Car[4];
public Garage()
{
cars[0] = new Car() { Id = Guid.NewGuid(), Name = "Corolla", Created = DateTime.UtcNow.AddHours(3), CurrentSpeed = 90 };
cars[1] = new Car() { Id = Guid.NewGuid(), Name = "Mazda", Created = DateTime.UtcNow.AddHours(2), CurrentSpeed = 80 };
}
...
}
程序.cs
static void Main(string[] args)
{
Garage cars = new Garage();
Console.WriteLine("sorting array:");
Array.Sort(cars); // error occured
}
错误 2 参数 1:无法从 'Car' 转换为 'System.Array'