Properly exposing a List?

前端 未结 8 1458
谎友^
谎友^ 2021-02-02 01:20

I know I shouldn\'t be exposing a List in a property, but I wonder what the proper way to do it is? For example, doing this:

public static          


        
8条回答
  •  孤街浪徒
    2021-02-02 01:51

    I asked a similar question earlier:

    • Difference between List and Collection (CA1002, Do not expose generic lists)
    • Why does DoNotExposeGenericLists recommend that I expose Collection instead of List?

    Based on that I would recommend that you use the List internally, and return it as a Collection or IList. Or if it is only necessary to enumerate and not add or antyhing like that, IEnumerable.

    On the matter of being able to cast what you return in to other things, I would just say don't bother. If people want to use your code in a way that it was not intended, they will be able to in some way or another. I previously asked a question about this as well, and I would say the only wise thing to do is to expose what you intend, and if people use it in a different way, well, that is their problem :p Some related questions:

    • How should I use properties when dealing with List members (Especially this answer)
    • Encapsulation of for example collections

提交回复
热议问题