List or BusinessObjectCollection?

后端 未结 18 1170
庸人自扰
庸人自扰 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:52

    Use the type List where you have to declare a list of them. However, where you return a list of BusinessObject, consider returning IEnumerable, IList or ReadOnlyCollection - i.e. return the weakest possible contract that satisfies the client.

    Where you want to "add custom code" to a list, code extension methods on the list type. Again, attach these methods to the weakest possible contract, e.g.

    public static int SomeCount(this IEnumerable someList)
    

    Of course, you can't and shouldn't add state with extension methods, so if you need to add a new property and a field behind it, use a subclass or better, a wrapper class to store this.

提交回复
热议问题