電商核心模組購物車的 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);
}
}
// 加入購物車
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> 獲得強型別與效能優勢