我有 3 种具有相同基类的对象。制作具有相同基类的对象数组的最佳方法是什么?我是否必须创建泛型类型并使用 Comparer 来执行此操作,或者有一种方法可以改用某些 arraylist 类?
我需要按类型和字段对对象进行排序。像这样:coupe1,coupe2,sedan1, sedan2,sedan3,hatchback1 等以及所有数组元素的字段。
class Program
{
abstract class Car
{
public string Name { get; set; }
public int Maxspeed { get; set; }
public override string ToString() { return Name + " | " + Maxspeed.ToString();}
}
class Coupe : Car
{
public Coupe(string name, int maxspeed){ Name = name; Maxspeed = maxspeed;}
}
class Sedan : Car
{
public Sedan(string name, int maxspeed) { Name = name; Maxspeed = maxspeed;}
}
class Hatchback : Car
{
public Hatchback(string name, int maxspeed){ Name = name; Maxspeed = maxspeed;}
}
class Cars<T>:IComparer<T> where T:Car
{
private T[] cars;
private int length;
public int Length
{
get{ return length;}
}
public Cars(int i)
{
if (i > 0){ cars = new T[i]; length = i;}\
}
public T this[int i]
{
get {return cars[i];}
set{cars[i] = value;}
}
public int Compare(T x, T y)
{
throw new NotImplementedException();
}
}
static void Main(string[] args)
{
Coupe coupe1 = new Coupe("Audi R8", 250);
Sedan sedan1 = new Sedan("Suzuki Ciaz", 180);
Hatchback hatchback1 = new Hatchback("Hyundai Elantra", 170);
Cars<Car> cars = new Cars<Car>(3);
cars[0] = coupe1;
cars[1] = sedan1;
cars[2] = hatchback1;
for (int i = 0; i < cars.Length; i++)
Console.WriteLine(cars[i].Name + " " + cars[i].Maxspeed.ToString());
Console.ReadKey();
}
}
如果您刚刚拥有一个,List<Car>
您可以使用 LINQ 先按OrderBy
类型排序,然后再按其他任何类型排序
Coupe coupe1 = new Coupe("Audi R8", 250);
Sedan sedan1 = new Sedan("Suzuki Ciaz", 180);
Hatchback hatchback1 = new Hatchback("Hyundai Elantra", 170);
List<Car> cars = new List<Car>(3);
cars.Add(coupe1);
cars.Add(sedan1);
cars.Add(hatchback1);
var orderedByTypeThenSpeedDescending = cars.OrderBy(x => x.GetType())
.ThenByDescending(x => x.MaxSpeed);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句