为什么 C# 队列或列表只有计数而数组有长度?
why C# queue or list only has count but array has length?
这可能是一个愚蠢的问题,为什么队列或列表没有长度属性,而只有计数?同样为什么数组有 Length 属性?
谢谢
数组是固定大小的,它们总是通过预先定义大小来初始化。
.Length
在这里是有意义的,因为它是固定的,没有涉及知道这一点的操作(认为没有计数)
与 .Count
另一方面意味着大小是动态的并且涉及(计数)操作以了解大小
Why there is no .Length
property for a Collection
or List
?
这确实是个好问题,部分答案与上面不同,但也受框架设计本身的影响
在框架设计中,一个Collection是Enumerable
,任何Enumerable
都有一个Enumerator
列表或集合的计数通过获取集合的枚举器,然后在递增计数器的同时迭代项目来工作
这是 System.Linq
扩展
中 .Count()
方法的实现
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
这可能是一个愚蠢的问题,为什么队列或列表没有长度属性,而只有计数?同样为什么数组有 Length 属性?
谢谢
数组是固定大小的,它们总是通过预先定义大小来初始化。
.Length
在这里是有意义的,因为它是固定的,没有涉及知道这一点的操作(认为没有计数)
与 .Count
另一方面意味着大小是动态的并且涉及(计数)操作以了解大小
Why there is no
.Length
property for aCollection
orList
?
这确实是个好问题,部分答案与上面不同,但也受框架设计本身的影响
在框架设计中,一个Collection是Enumerable
,任何Enumerable
都有一个Enumerator
列表或集合的计数通过获取集合的枚举器,然后在递增计数器的同时迭代项目来工作
这是 System.Linq
扩展
.Count()
方法的实现
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}