基于C#的停车场管理系统实现
基于C#的停车场管理系统实现
一、系统架构设计
// 核心类结构设计
public class ParkingSystem {private ParkingLot _parkingLot; // 停车场实体private VehicleManager _vehicleMgr; // 车辆管理private FeeCalculator _feeCalculator; // 计费模块private AccessLog _accessLog; // 日志系统
}public class ParkingLot {public int TotalSpots { get; set; }public int AvailableSpots { get; set; }public Dictionary<string, Vehicle> ParkedVehicles { get; } = new();
}
二、核心功能实现
1. 数据库交互模块(使用SQL Server)
// DBHelper.cs 数据库操作基类
public class DBHelper {private static string connectionString = "Server=localhost;Database=ParkingDB;Trusted_Connection=True;";public static DataTable Query(string sql, SqlParameter[] parameters = null) {using (SqlConnection conn = new SqlConnection(connectionString))using (SqlCommand cmd = new SqlCommand(sql, conn)) {cmd.Parameters.AddRange(parameters);conn.Open();SqlDataAdapter adapter = new SqlDataAdapter(cmd);DataTable dt = new DataTable();adapter.Fill(dt);return dt;}}public static int ExecuteNonQuery(string sql, SqlParameter[] parameters = null) {using (SqlConnection conn = new SqlConnection(connectionString))using (SqlCommand cmd = new SqlCommand(sql, conn)) {cmd.Parameters.AddRange(parameters);conn.Open();return cmd.ExecuteNonQuery();}}
}
2. 车辆管理模块
// Vehicle.cs 车辆实体类
public class Vehicle {public string LicensePlate { get; set; } // 车牌号public DateTime EntryTime { get; set; } // 进入时间public VehicleType Type { get; set; } // 车辆类型public string ParkingSpot { get; set; } // 停车位编号
}// VehicleManager.cs 车辆管理
public class VehicleManager {public bool EnterVehicle(Vehicle vehicle) {// 检查车位可用性if (CheckAvailability(vehicle.Type)) {vehicle.EntryTime = DateTime.Now;// 分配车位逻辑AssignParkingSpot(vehicle);return true;}return false;}public decimal CalculateFee(Vehicle vehicle) {TimeSpan duration = DateTime.Now - vehicle.EntryTime;return _feeCalculator.Calculate(duration, vehicle.Type);}
}
3. 智能计费模块
// FeeCalculator.cs 计费引擎
public class FeeCalculator {private decimal _baseRate = 5.00m; // 基础费率(元/小时)public decimal Calculate(TimeSpan duration, VehicleType type) {decimal rate = _baseRate;// 根据车型调整费率switch (type) {case VehicleType.Large:rate *= 1.5m;break;case VehicleType.Motorcycle:rate *= 0.5m;break;}decimal hours = Math.Ceiling(duration.TotalHours);return hours * rate;}
}
4. 停车位管理模块
// ParkingSpotManager.cs 车位管理
public class ParkingSpotManager {private Dictionary<string, SpotStatus> _spots = new();public void InitializeSpots(int totalSpots) {for (int i = 1; i <= totalSpots; i++) {_spots[$"P{i:00}"] = SpotStatus.Empty;}}public string FindNearestSpot(VehicleType type) {// 优先分配对应车型车位var availableSpots = _spots.Where(s => s.Value == SpotStatus.Empty && (type == VehicleType.Car || s.Key.StartsWith("M"))).ToList();return availableSpots.FirstOrDefault()?.Key ?? "无可用车位";}
}public enum SpotStatus { Empty, Occupied }
三、完整系统实现流程
- 系统初始化
static void Main(string[] args) {ParkingSystem system = new ParkingSystem();system.Init(100, 20, 50); // 总车位100,大车位20,摩托车位50// 加载历史数据var vehicles = DBHelper.Query("SELECT * FROM ParkedVehicles");foreach (DataRow row in vehicles.Rows) {system.LoadVehicle(new Vehicle {LicensePlate = row["Plate"].ToString(),EntryTime = (DateTime)row["EntryTime"]});}
}
- 车辆入场流程
public bool ProcessEntry(string plate) {if (!_vehicleMgr.IsVehicleRegistered(plate)) {_accessLog.Record($"未登记车辆尝试进入: {plate}");return false;}Vehicle vehicle = _vehicleMgr.GetVehicle(plate);if (system.AssignSpot(vehicle)) {_accessLog.Record($"车辆入场: {plate},车位 {vehicle.ParkingSpot}");return true;}return false;
}
- 车辆离场流程
public decimal ProcessExit(string plate) {Vehicle vehicle = _vehicleMgr.GetVehicle(plate);if (vehicle == null) return 0;decimal fee = _feeCalculator.Calculate(vehicle);_parkingLot.ReleaseSpot(vehicle.ParkingSpot);// 生成电子票据string receipt = GenerateReceipt(vehicle, fee);_accessLog.Record($"车辆离场: {plate},费用 {fee:C},票据已生成");return fee;
}
四、扩展功能实现
1. 车牌识别集成
// 调用百度AI车牌识别API
public string RecognizePlate(string imagePath) {using (var client = new HttpClient()) {var response = client.PostAsync("https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate", new StringContent($"access_token={accessToken}&image={Convert.ToBase64String(File.ReadAllBytes(imagePath))}")).Result.Content.ReadAsStringAsync().Result;JObject json = JObject.Parse(response);return json["words_result"][0]["number"].ToString();}
}
2. 移动支付对接
// 微信支付接口
public bool ProcessWeChatPay(string orderId, decimal amount) {string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";var parameters = new Dictionary<string, string> {{ "appid", wechatAppId },{ "mch_id", mchId },{ "nonce_str", Guid.NewGuid().ToString("N") },{ "body", "停车费支付" },{ "out_trade_no", orderId },{ "total_fee", (amount * 100).ToString() },{ "spbill_create_ip", HttpContext.Connection.RemoteIpAddress.ToString() },{ "notify_url", "https://yourdomain.com/pay/notify" },{ "trade_type", "NATIVE" }};// 签名生成与请求发送逻辑...
}
五、系统部署建议
-
环境要求
- 开发环境:Visual Studio 2022 + .NET 6.0
- 数据库:SQL Server 2019 或 MySQL 8.0
- 硬件:支持RFID读卡器/摄像头外设
-
安全配置
<!-- appsettings.json --> {"Security": {"DbConnectionString": "EncryptedString","PaymentKey": "RSA加密密钥"} }
-
监控仪表盘
// 实时车位状态显示 public void UpdateDashboard() {int occupied = _parkingLot.OccupiedSpots;int available = _parkingLot.TotalSpots - occupied;Console.ForegroundColor = ConsoleColor.Green;Console.WriteLine($"当前车位:{available}/{_parkingLot.TotalSpots}");Console.ResetColor(); }
参考项目代码 c# 停车场管理系统源码 www.youwenfan.com/contentcsi/62680.html
六、技术难点解析
-
并发控制
使用
SemaphoreSlim
控制同时访问:private SemaphoreSlim _parkingLock = new(1, 1);public async Task<bool> SafeEnterVehicle(Vehicle vehicle) {await _parkingLock.WaitAsync();try {return _vehicleMgr.EnterVehicle(vehicle);} finally {_parkingLock.Release();} }
-
数据持久化
使用Entity Framework Core实现ORM:
public class ParkingContext : DbContext {public DbSet<Vehicle> Vehicles { get; set; }public DbSet<ParkingSpot> Spots { get; set; }protected override void OnConfiguring(DbContextOptionsBuilder options) {options.UseSqlServer("YourConnectionString");} }