gpt4 book ai didi

c# - 为什么 IList 不包含 Length 属性?

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:24 24 4
gpt4 key购买 nike

我试着这样做:

int listAverage = NumberList.Sum()/NumberList.Length;

哪里NumberList是一个 IList .它抛出一个错误:

'System.Collections.Generic.IList' does not contain a definition for 'Length' and no extension method 'Length' accepting a first argument of type 'System.Collections.Generic.IList' could be found (are you missing a using directive or an assembly reference?)

这让我开始思考,why does List<T> not have a Length property ?我知道你可以使用 Count()相反,但是 Length时间复杂度为 O(1)。

最佳答案

根据我的经验,.NET 中的约定似乎是数组和字符串具有 Length 属性,更高级别的可数集合具有 Count 属性。 IList<T> 有一个 Count 属性,一般应该 O(1),但取决于确切的实现。例如,最常用的 List<T> 确实在 O(1) 时完成。

通用 Count() 方法是任何 IEnumerable<T> 类型的扩展,技术上确实具有 O(n) 的复杂性,因为在枚举每个元素之前可能不知道项目的数量,或者给出数字需要一些自定义处理(比如例如,由 IQueryable<T> 接口(interface)表示的 Linq to SQL 查询结果)。

关于c# - 为什么 IList<T> 不包含 Length 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com