首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 購物車類實作:Hashtable 管理商品與金額計算

     編輯:關於ASP.NET

電商核心模組購物車的 C# 實作,使用 Hashtable 以商品 ID 為鍵管理 Stat_Class 商品實體,支援新增、刪除、列舉與總價計算,序列化支援 Session 持久化。

核心類別設計

[Serializable]
public class Stat_Class
{
    public string ItemID { get; set; }      // 商品 ID
    public string ShangpinName { get; set; } // 商品名稱
    public decimal Price { get; set; }       // 單價
    public int Quantity { get; set; }        // 數量

    public Stat_Class(string id, string name, decimal price, int qty)
    {
        ItemID = id; ShangpinName = name; Price = price; Quantity = qty;
    }
}

[Serializable]
public class ShoppingCart
{
    private Hashtable Cart_Orders = new Hashtable();

    public ICollection Orders => Cart_Orders.Values;

    public decimal TotalCost
    {
        get
        {
            decimal total = 0;
            foreach (DictionaryEntry entry in Cart_Orders)
            {
                Stat_Class item = (Stat_Class)entry.Value;
                total += item.Price * item.Quantity;
            }
            return total;
        }
    }

    public void AddItem(Stat_Class order)
    {
        Stat_Class existing = (Stat_Class)Cart_Orders[order.ItemID];
        if (existing != null)
            existing.Quantity += order.Quantity;  // 合併同商品數量
        else
            Cart_Orders.Add(order.ItemID, order);
    }

    public void DeleteItem(string itemID)
    {
        if (Cart_Orders[itemID] != null)
            Cart_Orders.Remove(itemID);
    }
}

關鍵設計決策

  • Hashtable 而非 List:O(1) 查找合併同商品,避免重複項目
  • [Serializable]:支援 Session、ViewState、檔案序列化持久化
  • 商品實體封裝:擴充屬性(圖片、規格、庫存)不影響購物車邏輯
  • 總價計算屬性:即時計算,無需額外同步欄位

使用範例

// 加入購物車
ShoppingCart cart = Session["Cart"] as ShoppingCart ?? new ShoppingCart();
cart.AddItem(new Stat_Class("P001", "筆記型電腦", 25000m, 1));
Session["Cart"] = cart;

// 顯示購物車
foreach (Stat_Class item in cart.Orders)
{
    Response.Write($"{item.ShangpinName} x {item.Quantity} = {item.Price * item.Quantity:C}<br>");
}
Response.Write($"總計:{cart.TotalCost:C}");

擴充建議

  • 新增 UpdateQuantity(string id, int qty) 修改數量
  • 加入 Clear() 清空購物車
  • 實作 GetCount() 取得商品種類數
  • 整合優惠券、運費、稅金計算邏輯
  • 考慮改用 Dictionary<string, Stat_Class> 獲得強型別與效能優勢
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved