计算列表字典中所有对象的总成本
本文关键字:对象 总成本 列表 字典 计算 | 更新日期: 2023-09-27 18:32:45
我是 C# 的编程学生,我被要求编写一个应用程序,但我无法弄清楚如何获取所有对象并计算总价格。
如果您可以将我引用到另一个页面或答案,任何帮助都会很好
谢谢它public decimal TotalCost()
namespace GCUShows
{
public class Booking
{
private const int LIMIT = 6;
// TODO: This class should include the following:
// instance variable show which is a reference to a Show object
public Show show;
private int bookingID;
public List<ITicket> tickets;
public int BookingID
{
get { return bookingID; }
set { bookingID = value; }
}
public Booking(Show show)
{
this.BookingID = BookingIDSequence.Instance.NextID;
this.show = show;
show.AddBooking(this);
this.tickets = new List<ITicket>();
}
public void AddTickets(int number, TicketType type, decimal fee)
{
// TODO:this method should instantiate the specified number of tickets of the
// specified type and add these to the list of tickets in this booking
if (type == TicketType.Adult)
{
for(int i =0; i < number; i++)
{
tickets.Add(new AdultTicket(show.Title, fee));
}
}
else if (type == TicketType.Child)
{
for(int i=0; i< number; i++)
{
tickets.Add(new ChildTicket(show.Title));
}
}
else if (type == TicketType.Family)
{
for (int i = 0; i < number; i++)
{
tickets.Add(new FamilyTicket(show.Title, fee));
}
}
}
public string PrintTickets()
{
string ticketInfo = "Booking " + bookingID.ToString() + "'n";
foreach (ITicket ticket in tickets)
{
ticketInfo += ticket.Print();
}
return ticketInfo;
}
public decimal TotalCost()
{
// TODO: this method should return the total cost of the tickets in this booking
}
public override string ToString()
{
return string.Format("{0}: Total Cost={1:c}", bookingID, TotalCost());
}
}
}
假设 ITicket
中有一个 Cost
属性,您可以使用 LINQ(在文件顶部添加using System.Linq
(:
tickets.Select(x => x.Cost).Sum();
甚至简单地:
tickets.Sum(x => x.Cost);
您需要一种方法来查找您拥有的所有门票,并逐个浏览它们以找到运行总数。
如果您查看已声明的变量(以及调用 AddTicket 时使用的变量(,您认为什么合适?
<块引用类> 您的public List<ITicket> tickets;
,因为它包含我们所有门票的列表
然后,我们需要使用迭代器(将依次查看每个对象的东西(将所有总数相加。我们在代码中的其他任何地方都这样做了吗?
<块引用类> 查看我们的 Print 方法 - 它使用 foreach 循环迭代遍历我们的集合 foreach (ITicket ticket in tickets)
{
ticketInfo += ticket.Print();
}
然后,您可以将其与 ITicket 上的成本属性相结合以获得运行总计,例如
<块引用类> Decimal totalCost;
foreach (ITicket ticket in tickets)
{
totalCost += ticket.Fee;
}
return totalCost;
切中要害:
您已经在以打印方法迭代您的票证。使用类似的东西将所有费用相加并返回结果1。
<块引用类>
decimal totalPrice = 0.0m;
foreach (ITicket ticket in tickets)
{
totalPrice += ticket.Fee;
}
return totalPrice;
一些建设性的批评:
BookingIDSequence
singelton 真的没有必要,除非您在Booking
类之外使用它。如果您只保留预订 ID 的计数,请考虑将其作为Booking
类的静态属性,并在Booking
构造函数中分配/递增它。- 如果您决定保留它,并且尽管这可能是语义上的,最好使用带有动词的方法来明确其目的(例如
.GetNextId()
超过.NextId
(然后任何使用该类的人都明白发生了什么。
机票- 如果您决定保留它,并且尽管这可能是语义上的,最好使用带有动词的方法来明确其目的(例如
- 费用应移至机票舱位本身。当您添加子票证时,
fee
参数变得无用(但仍是必需的(。此外,门票和费用是 1:1,将它们分开是有意义的。- 您甚至可以使用
AddDiscount(Decimal percent)
等业务逻辑扩展ITicket
。
- 您甚至可以使用
- 与其在
AddTickets
中使用 if 语句,不如查看 switch 语句。这是一个非此即彼的决定,但对于枚举,它们通常看起来更干净。 - 与
NextId
相同,TotalCost
更简洁地重命名为GetTotalCost()
。
额外学分:
- 查看在打印方法中使用
StringBuilder
。 - 查找用于创建
ITicket
类型的工厂模式。