Skip to main content
 首页 » 编程设计

c#之linq 扩展方法 ElementAt 的性能

2024年02月24日45cyq1162

Enumerable.ElementAt(TSource) 方法的 MSDN 库条目说

"If the type of source implements IList, that implementation is used to obtain the element at the specified index. Otherwise, this method obtains the specified element."

假设我们有以下示例:

        ICollection<int> col = new List<int>() { /* fill with items */ }; 
        IList<int> list = new List<int>() { /* fill with items */ }; 
 
        col.ElementAt(10000000); 
        list.ElementAt(10000000); 

执行上有什么不同吗?或者 ElementAt 是否认识到 col 也实现了 IList<>,尽管它只被声明为 ICollection<>?

谢谢

请您参考如下方法:

变量本身的类型与ElementAt无关方法 - 就而言,它仅声明为 IEnumerable<T> ,因为这就是参数类型。 (两个调用将绑定(bind)到相同的扩展方法。)

它是在 ElementAt 中测试的对象的执行时类型.