List or BusinessObjectCollection?

后端 未结 18 1020
庸人自扰
庸人自扰 2020-12-23 11:11

Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable

IE:

publi         


        
18条回答
  •  一生所求
    2020-12-23 11:39

    You can use both. For laziness - I mean productivity - List is a very useful class, it's also "comprehensive" and frankly full of YANGNI members. Coupled with the sensible argument / recommendation put forward by the MSDN article already linked about exposing List as a public member, I prefer the "third" way:

    Personally I use the decorator pattern to expose only what I need from List i.e:

    public OrderItemCollection : IEnumerable 
    {
        private readonly List _orderItems = new List();
    
        void Add(OrderItem item)
        {
             _orderItems.Add(item)
        }
    
        //implement only the list members, which are required from your domain. 
        //ie. sum items, calculate weight etc...
    
        private IEnumerator Enumerator() {
            return _orderItems.GetEnumerator();
        }
    
        public IEnumerator GetEnumerator() {
            return Enumerator();
        }    
    }
    

    Further still I'd probably abstract OrderItemCollection into IOrderItemCollection so I can swap my implementation of IOrderItemCollection over in the future in (I may prefer to use a different inner enumerable object such as Collection or more likley for perf use a Key Value Pair collection or Set.

提交回复
热议问题