Why use IList or List?

后端 未结 10 689
离开以前
离开以前 2020-11-29 15:58

I know there has been a lot of posts on this but it still confuses me why should you pass in an interface like IList and return an interface like IList back instead of the c

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 16:41

    There are three questions here: what type should I use for a formal parameter? What should I use for a local variable? and what should I use for a return type?

    Formal parameters:

    The principle here is do not ask for more than you need. IEnumerable communicates "I need to get the elements of this sequence from beginning to end". IList communicates "I need to get and set the elements of this sequence in arbitrary order". List communicates "I need to get and set the elements of this sequence in arbitrary order and I only accept lists; I do not accept arrays."

    By asking for more than you need, you (1) make the caller do unnecessary work to satisfy your unnecessary demands, and (2) communicate falsehoods to the reader. Ask only for what you're going to use. That way if the caller has a sequence, they don't need to call ToList on it to satisfy your demand.

    Local variables:

    Use whatever you want. It's your method. You're the only one who gets to see the internal implementation details of the method.

    Return type:

    Same principle as before, reversed. Offer the bare minimum that your caller requires. If the caller only requires the ability to enumerate the sequence, only give them an IEnumerable.

提交回复
热议问题