IEnumerable vs T[]

前端 未结 7 1262
天命终不由人
天命终不由人 2021-01-07 20:43

I just realize that maybe I was mistaken all the time in exposing T[] to my views, instead of IEnumerable.

Usually, for this kind

相关标签:
7条回答
  • 2021-01-07 21:13

    It's partially inconsequential, but standard theory would dictate "Program against an interface, not an implementation". With the interface model you can change the actual datatype being passed without effecting the caller as long as it conforms to the same interface.

    The contrast to that is that you might have a reason for exposing an array specifically and in which case would want to express that.

    For your example I think IEnumerable<T> would be desirable. It's also worthy to note that for testing purposes using an interface could reduce the amount of headache you would incur if you had particular classes you would have to re-create all the time, collections aren't as bad generally, but having an interface contract you can mock easily is very nice.

    Added for edit:
    This is more inconsequential because the underlying datatype is what will implement the Count() method, for an array it should access the known length, I would not worry about any perceived overhead of the method. See Jon Skeet's answer for an explanation of the Count() implementation.

    0 讨论(0)
提交回复
热议问题