我正在制作代表汽车零件商店的控制台应用程序,我有一个包含零件和其他耗材的目录。
当我输入“返回成本高到低”这样的命令时,如何将所有产品的成本从最高到最低,以及每个部件的名称按顺序排列?
这是相关的代码:
public class AutoPart
{
public string Name;
public double Cost;
}
public class Liquid : AutoPart
{
public new string Name;
public new double Cost;
public double Quarts;
}
public class tool : AutoPart
{
public new string Name;
public new double Cost;
public double SizeInMM;
}
public class Catalogue
{
static void Main(string[] args)
{
AutoPart Motorcraftoilfilter = new AutoPart();
Motorcraftoilfilter.Name = "MotorCraft Oil Filter";
Motorcraftoilfilter.Cost = 6.99;
Liquid valvolineoil = new Liquid();
valvolineoil.Name = "Valvoline Oil";
valvolineoil.Cost = 8.99;
valvolineoil.Quarts = 1;
tool Wrench = new tool();
Wrench.Name = "Duralast 13mm Wrench";
Wrench.Cost = 16.99;
Wrench.SizeInMM = 13;
}
}
删除子类中不必要的字段,因为它们继承自AutoPart。
public class Liquid : AutoPart
{
public string FluidType; //this defines the type of fluid the product
public double Quarts; //this defines the quarts of the object
}
public class tool : AutoPart
{
public double sizeinmm; //this declares the size of the tool in milimeters
}
创建一个列表以包含所有汽车零部件
List<AutoPart> AllAutoParts = new List<AutoPart>
{
Motorcraftoilfilter,
valvolineoil,
Wrench,
};
然后你就可以完成这项工作
if (Console.ReadLine() == "Return Price High to low")
{
foreach (var autopart in AllAutoParts.OrderByDescending(autopart => autopart.Cost))
Console.WriteLine("Cost: {0}, Name: {1}", autopart.Cost, autopart.Name);
}
正如shingo所提到的,您可以创建基类类型列表(AutoPart
)并将所有其他类型添加到其中。您只能按顺序使用基类属性,但由于它包含Cost
和Name
属性,因此您应该能够执行所需的操作。
然后,您可以使用OrderByDescending
扩展方法(将using System.Linq
添加到文件的顶部),按Cost
从高到低排序:
private static void Main(string[] cmdArgs)
{
AutoPart motorCraftOilFilter = new AutoPart();
motorCraftOilFilter.Name = "MotorCraft Oil Filter";
motorCraftOilFilter.Cost = 6.99;
Liquid valvolineOil = new Liquid();
valvolineOil.Name = "Valvoline Oil";
valvolineOil.Cost = 8.99;
valvolineOil.Quarts = 1;
Tool wrench = new Tool();
wrench.Name = "Duralast 13mm Wrench";
wrench.Cost = 16.99;
wrench.SizeInMM = 13;
var catalog = new List<AutoPart>
{
motorCraftOilFilter,
valvolineOil,
wrench
};
// Pretent the command to order products was entered
// You can use OrderByDescending to order the items by
// Cost from Highest to Lowest
catalog = catalog.OrderByDescending(part => part.Cost).ToList();
// Output results
catalog.ForEach(item => Console.WriteLine(item.Name + " " + item.Cost));
Console.Write("\nPress any key to exit...");
Console.ReadKey();
}
关于设计类的方法需要注意的一点是,您不需要创建已在基类中定义的new
字段。这是使用继承的原因之一是您自动继承这些字段。
此外,根据经验,您应该几乎总是使用属性而不是公共成员的字段。你可以阅读有关here的原因。
这样,您的类更简单 - 只为子类添加唯一属性:
public class AutoPart
{
public string Name { get; set; }
public double Cost { get; set; }
}
public class Liquid : AutoPart
{
public double Quarts { get; set; }
}
public class Tool : AutoPart
{
public double SizeInMM { get; set; }
}