Is returning IList worse than returning T[] or List?

前端 未结 5 2148
心在旅途
心在旅途 2020-12-12 12:38

The answers to questions like this: List or IList always seem to agree that returning an interface is better than returning a concrete implementation of a

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 13:31

    As with all "interface versus implementation" question, you'll have to realise what exposing a public member means: it defines the public API of this class.

    If you expose a List as a member (field, property, method, ...), you tell the consumer of that member: the type obtained by accessing this method is a List, or something derived of that.

    Now if you expose an interface, you hide the "implementation detail" of your class using a concrete type. Of course you can't instantiate IList, but you can use an Collection, List, derivations thereof or your own type implementing IList.

    The actual question is "Why does Array implement IList", or "Why has the IList interface so many members".

    It also depends on what you want the consumers of that member to do. If you actually return an internal member through your Expose... member, you'll want to return a new List(internalMember) anyway, as otherwise the consumer can try and cast them to IList and modify your internal member through that.

    If you just expect consumers to iterate the results, expose IEnumerable or IReadOnlyCollection instead.

提交回复
热议问题