IList and IReadOnlyList

后端 未结 4 1962
小鲜肉
小鲜肉 2021-02-01 02:20

If I have a method that requires a parameter that,

  • Has a Count property
  • Has an integer indexer (get-only)

What should the type

4条回答
  •  星月不相逢
    2021-02-01 02:28

    Since IList and IReadOnlyList do not share any useful "ancestor", and if you don't want your method to accept any other type of parameter, the only thing you can do is provide two overloads.

    If you decide that reusing codes is a top priority then you could have these overloads forward the call to a private method that accepts IEnumerable and uses LINQ in the manner Daniel suggests, in effect letting LINQ do the normalization at runtime.

    However IMHO it would probably be better to just copy/paste the code once and just keep two independent overloads that differ on just the type of argument; I don't believe that micro-architecture of this scale offers anything tangible, and on the other hand it requires non-obvious maneuvers and is slower.

提交回复
热议问题