这篇是对象与集合操练,物件的创建,集合的一些基本功能,如添加,编辑,删除等功能。
对象,即是网店的商品物件,Insus.NET只为其添加2个属性,物件的ID的Key和名称ItemName以及2个构造函数,最后一个方法是重写ToString()方法。
class Item { private int _key; public int Key { get { return _key; } set { _key = value; } } private string _ItemName; public string ItemName { get { return _ItemName; } set { _ItemName = value; } } public Item() { } public Item(int key, string itemName) { this._key = key; this._ItemName = itemName; } public override string ToString() { return string.Format("ID: {0}; Name: {1}。",_key,_ItemName); } }
有了物件,你可以创建你的购物车Shopping Cart:
class ShoppingCart { private SortedList<int, Item> _sl = new SortedList<int, Item>(); public void Add(Item item) //物件添加 { this._sl.Add(item.Key, item); } public void Edit(Item item) //编辑物件 { if (this._sl.ContainsKey(item.Key)) { this._sl[item.Key] = item; } } public void Delete(Item item) //删除物件 { this._sl.Remove(item.Key); } public Item this[int key] //索引器 { get { if (!this._sl.ContainsKey(key)) { return null; } else { return this._sl[key]; } } } public virtual int Count //集合中物件数量 { get { return this._sl.Count; } } public virtual IEnumerable<Item> Items //获取所有物件 { get { return this._sl.Values; } } }
class Program { static void Main(string[] args) { ShoppingCart sc = new ShoppingCart(); var item1 = new Collections.Item(); item1.Key = 1; item1.ItemName = "Huawei V8"; sc.Add(item1); var item2 = new Collections.Item(); item2.Key = 2; item2.ItemName = "Huawei V9"; sc.Add(item2); var item3 = new Collections.Item(); item3.Key = 3; item3.ItemName = "Huawei V10"; sc.Add(item3); Console.WriteLine("使用索引器,输出对象:"); Console.WriteLine(sc[3].ToString()); Console.WriteLine("集合中对象数量:"); Console.WriteLine(sc.Count); Console.WriteLine("列出所有对象:"); sc.Items.ForEach(delegate (Collections.Item item) { Console.WriteLine(item.ToString()); }); } }
按Ctrl + F5输出结果:
最后演示编辑Edit和删除Delete的功能:
var item4 = new Collections.Item(); item4.Key = 2; item4.ItemName = "Huawei Mate10"; sc.Edit(item4); Console.WriteLine("编辑后列出所有对象:"); sc.Items.ForEach(delegate (Collections.Item item) { Console.WriteLine(item.ToString()); }); var item5 = new Collections.Item(); item5.Key = 1; sc.Delete(item5); Console.WriteLine("删除后列出所有对象:"); sc.Items.ForEach(delegate (Collections.Item item) { Console.WriteLine(item.ToString()); });
运行看看结果: