IList and IReadOnlyList

后端 未结 4 1965
小鲜肉
小鲜肉 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:40

    You are out of luck here. IList doesn't implement IReadOnlyList. List does implement both interfaces, but I think that's not what you want.

    However, you can use LINQ:

    • The Count() extension method internally checks whether the instance in fact is a collection and then uses the Count property.
    • The ElementAt() extension method internally checks whether the instance in fact is a list and than uses the indexer.

提交回复
热议问题