用c#写一个简单的购票系统
时间: 2024-11-24 21:43:04 浏览: 17
在C#中编写一个简单的购票系统,可以包括以下几个步骤和类:
1. 定义基础类(如座位基类Seat)
```csharp
public abstract class Seat
{
public string Id { get; set; }
public bool IsBooked { get; protected set; }
public Seat(string id)
{
Id = id;
IsBooked = false;
}
public virtual void Book()
{
if (!IsBooked)
IsBooked = true;
else
throw new Exception("该座位已预订");
}
public virtual void Cancel()
{
if (IsBooked)
IsBooked = false;
else
throw new Exception("该座位未预订");
}
}
```
2. 创建具体的座位类(如商务舱、经济舱等)
```csharp
public class BusinessClassSeat : Seat
{
// 可能增加额外属性如价格
}
public class EconomyClassSeat : Seat
{
// 可能增加额外属性如价格
}
```
3. 主程序入口(售票窗口类TicketOffice)
```csharp
class TicketOffice
{
private List<Seat> seats;
public TicketOffice()
{
seats = new List<Seat>();
// 初始化座位列表
}
public void Sell(BusinessClassSeat seat)
{
if (seat.IsBooked)
throw new Exception("座位已售出");
seat.Book();
Console.WriteLine($"商务舱座位{seat.Id}已售出");
}
public void Sell(EconomyClassSeat seat)
{
if (seat.IsBooked)
throw new Exception("座位已售出");
seat.Book();
Console.WriteLine($"经济舱座位{seat.Id}已售出");
}
public void Cancel(BookableSeat seat)
{
seat.Cancel();
Console.WriteLine($"座位{seat.Id}已取消预订");
}
}
```
4. 使用示例
```csharp
public static void Main(string[] args)
{
var ticketOffice = new TicketOffice();
ticketOffice.seats.Add(new BusinessClassSeat("B001"));
ticketOffice.seats.Add(new EconomyClassSeat("E001"));
ticketOffice.Sell(ticketOffice.seats[0]); // 商务舱
ticketOffice.Sell(ticketOffice.seats[1]); // 经济舱
// 模拟取消预订
ticketOffice.Cancel(ticketOffice.seats[0]);
}
```
阅读全文