Something in the likes of IList.IndexOf() but on IEnumerable?

前端 未结 3 1629
旧巷少年郎
旧巷少年郎 2021-02-20 12:17

Is there any method / extension method on IEnumerable that allows me to find the index of of an object instance in it? Like IndexOf() in IList?

indexPosition = m         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 12:37

    Note that there couldn't be any instance method because IEnumerable is covariant.

    Anything of type IEnumerable has to implement IndexOf(string x), and, due to covariance, can be casted to IEnumerable.

    So it now exposes as IndexOf(object x) what is really IndexOf(string x), and since not all objects are strings, couldn't work for all objects.

    IList can do it because it's invariant, i.e. you can't cast an IList to an IList.

    提交回复
    热议问题