当前位置: 首页 > news >正文

基于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 }

三、完整系统实现流程

  1. 系统初始化
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"]});}
}
  1. 车辆入场流程
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;
}
  1. 车辆离场流程
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" }};// 签名生成与请求发送逻辑...
}

五、系统部署建议

  1. 环境要求

    • 开发环境:Visual Studio 2022 + .NET 6.0
    • 数据库:SQL Server 2019 或 MySQL 8.0
    • 硬件:支持RFID读卡器/摄像头外设
  2. 安全配置

    <!-- appsettings.json -->
    {"Security": {"DbConnectionString": "EncryptedString","PaymentKey": "RSA加密密钥"}
    }
    
  3. 监控仪表盘

    // 实时车位状态显示
    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/contentcnk/62680.html

六、技术难点解析

  1. 并发控制

    使用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();}
    }
    
  2. 数据持久化

    使用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");}
    }
    
http://www.hskmm.com/?act=detail&tid=40363

相关文章:

  • 2025年市面上别墅石材品牌与行业内别墅石材源头厂家推荐榜单及口碑好的别墅石材产品分析
  • 连中五标,中电金信国际化服务助力企业出海
  • 1195. 交替打印字符串
  • 回调函数
  • gdb调试常用命令
  • 2025年10月中国管理咨询公司推荐榜:五强数据对比
  • 条码识别插件 quaggaJS - microsoft
  • 2025 年灵巧手厂家最新推荐榜,技术实力与市场口碑深度解析,筛选高适配性与长耐用性优质品牌
  • Dify工作流实战:一键自动生成测试报告并推送钉钉,我每天白赚1小时
  • CF2043D Problem about GCD
  • 一起为可信数据流通添砖加瓦,隐语社区 OSCP 专项开源活动正式启动!
  • 2025年10月精益管理咨询公司推荐:权威榜单与多维对比评测
  • 2025年10月降本增效咨询公司推荐:实力榜对比五家优劣势
  • CF2093G Shorten the Array
  • 2025年10月降本增效咨询公司推荐榜:五强数据横评
  • 2025 年水处理聚丙烯酰胺,聚丙烯酰胺水处理剂,工业废水处理聚丙烯酰胺厂家最新推荐,产能、专利、环保三维数据透视!
  • 2025 年阴离子聚丙烯酰胺,阳离子聚丙烯酰胺,非离子聚丙烯酰胺厂家最新推荐,产能、专利、环保三维数据透视
  • 2025 年聚丙烯酰胺絮凝剂,PAM 聚丙烯酰胺,聚丙烯酰胺聚合氯化铝厂家最新推荐,产能、专利、环保三维数据透视
  • ST表
  • 吱吱企业即时通讯:赋能企业高效沟通与协作新生态
  • Windows Server 2022 OVF (2025 年 10 月更新) - VMware 虚拟机模板
  • Linux运行时常用命令
  • 2025年盘式干燥机厂家权威推荐榜单:回转滚筒干燥机/真空干燥机/沸腾干燥机源头厂家精选
  • Windows Server 2025 OVF (2025 年 10 月更新) - VMware 虚拟机模板
  • 同步盘哪个好用?坚果云、百度网盘等五大工具横向对比
  • 借助 ChatGPT API 将 AI 集成到测试自动化框架中
  • P11994 [JOIST 2025] 外郎糕 题解
  • 告别手动上传!10款自动同步本地文件夹的网盘深度评测
  • 腾讯CodeBuddy:AI IDE的革命性突破,开发者工作方式的彻底重塑
  • C++中STL容器应用