代码重构之封装集合
核心:用IEnumerable<T> 而不是用 IList<T>
如果某个集合只是需要对外暴露查询的功能,那么就应该用IEnumerable<T> 而不是用 IList<T>来作为结果的返回。因为IList<T> 有对集合操作的所有功能(修改,删除等),而IEnumerable<T> 就只有对集合的遍历、取值的操作,不存在更改操作。
代码演示:
1、产品代码
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EncapsulateCollection { public class Product { public int id { get; set; } public string FullName { get; set; } public decimal Price { get; set; } } }
2、集合代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EncapsulateCollection { public class Order { public void InitList() { list = new List<Product>() { new Product() { id = 1, FullName ="冰箱", Price = 12000}, new Product() { id = 2, FullName = "烤箱", Price = 800 }, new Product() { id = 3, FullName = "微波炉", Price = 600 }, }; } private IList<Product> list; public IList<Product> GetProducts() { return list; } public IEnumerable<Product> OnlyGetProducts() { return list; } public void AddProduct(Product product) { list.Add(product); } public void RemoveProduct(Product product) { if (list.Contains(product)) { list.Remove(product); } } } }
3、调用代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// 封装集合 /// </summary> namespace EncapsulateCollection { class Program { static void Main(string[] args) { Order order = new Order(); order.InitList(); Console.WriteLine("==================集合用IList作为返回============="); IList<Product> products = order.GetProducts(); Product productItem = new Product() { id = 4, FullName = "苹果", Price = 12 }; products.Add(productItem); //新增集合元素 products.Remove(productItem); //删除集合元素 order.AddProduct(new Product() { id = 5, FullName = "不粘锅", Price = 199 }); foreach (var item in products) { Console.WriteLine(item.FullName); } Console.WriteLine("==================集合改用IEnumerable作为返回============="); order.InitList(); IEnumerable<Product> productList = order.OnlyGetProducts(); order.AddProduct(new Product() { id = 4, FullName = "刺身刀", Price = 500 }); foreach (var item in productList) { Console.WriteLine(item.FullName); } Console.Read(); } } }
结果展示:
写写博客,方便自己也方便有需要的人~~