我正在制作一个代表汽车零配件商店的控制台应用程序,并且我有一个包含零部件和其他供应品的目录。
当我输入像"Return Cost High to low“这样的命令时,我如何将所有产品的成本从最高到最低以及每个部件的名称排序?
相关代码如下:
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;
}
}
发布于 2018-09-14 11:40:51
删除子类中不必要的字段,因为它们继承自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);
}
发布于 2018-09-14 12:07:52
正如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; }
}
https://stackoverflow.com/questions/52324444
复制相似问题