Properly exposing a List?

前端 未结 8 1460
谎友^
谎友^ 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

    You don't need to worry about the overhead of cloning: wrapping a collection with a ReadOnlyCollection does not clone it. It just creates a wrapper; if the underlying collection changes, the readonly version changes also.

    If you worry about creating fresh wrappers over and over again, you can cache it in a separate instance variable.

    0 讨论(0)
  • 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<T> internally, and return it as a Collection<T> or IList<T>. Or if it is only necessary to enumerate and not add or antyhing like that, IEnumerable<T>.

    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
    0 讨论(0)
提交回复
热议问题