我是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());
}
}
}发布于 2014-12-02 15:36:12
假设Cost属性在ITicket中,您可以使用LINQ (在文件顶部添加using System.Linq ):
tickets.Select(x => x.Cost).Sum();甚至简单地说:
tickets.Sum(x => x.Cost);发布于 2014-12-02 15:50:37
好吧,你需要一个方法找到所有的票,然后一个接一个地看一遍,找出一个又一个的总票。
如果您查看声明的变量(并在调用AddTickets时使用),您认为什么是合适的?
你的
public List<ITicket> tickets;,因为它持有我们所有的票的列表
然后,我们需要使用一个Iterator (将依次查看每个对象)来将我们的总数加起来。我们在代码中的其他地方做过这件事吗?
查看我们的打印方法--它使用foreach循环
foreach (ITicket ticket in tickets){ticketInfo += ticket.Print();}迭代地遍历我们的集合。
然后,您可以将它与ITicket上的成本属性结合起来,以获得一个正在运行的总计,例如
Decimal totalCost;foreach (ITicket ticket in tickets){totalCost += ticket.Fee;}return totalCost;
https://stackoverflow.com/questions/27253117
复制相似问题