首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 中正確儲存商品資料:拋棄 ArrayList 改用泛型 List<T>

     編輯:程式設計綜合問答

為什麼不推薦 ArrayList

ArrayList 屬於非泛型集合,存入時會發生裝箱,取出需拆箱並強制轉型,效能差且易發生執行期錯誤。現代 C# 開發應優先使用 List<T>。

建立商品類別

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
}

使用 List<Product> 存取資料

var products = new List<Product>();
products.Add(new Product { Id = 1001, Name = "蘋果", Quantity = 10, Price = 1.2m });

// 1. 依商品編號查詢
var target = products.FirstOrDefault(p => p.Id == 1001);
if (target != null)
{
    Console.WriteLine($"{target.Name} - 單價: {target.Price}");
}

// 2. 修改庫存
target.Quantity -= 2;

// 3. 遍歷顯示
foreach (var p in products)
{
    Console.WriteLine($"{p.Id}\t{p.Name}\t{p.Quantity}\t{p.Price}");
}

進階:建立索引加速查詢

若資料量大且頻繁依 ID 查詢,可改用 Dictionary<int, Product>:

var dict = products.ToDictionary(p => p.Id);
Product p = dict[1001]; // O(1) 直接取得

總結

  • 定義強型別類別承載業務資料。
  • 使用 List<T> 管理集合,享受編譯期型別檢查與 IntelliSense。
  • 需高頻查詢時改用 Dictionary<K, V>。

這才是 C# 正統、高效、可維護的資料處理方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved