C# Array.Length 与 Array.Count
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1506963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array.Length vs Array.Count
提问by Joan Venge
Possible Duplicate:
count vs length vs size in a collection
可能的重复:
集合中的计数 vs 长度 vs 大小
In .NET, pretty much all collections have the .Count
property.
在 .NET 中,几乎所有集合都具有该.Count
属性。
Sometimes I wonder if it would be better to have it on Array
as well, directly though, not through ICollection
.
有时我想知道Array
直接打开它是否会更好,而不是通过ICollection
.
It's just something you make an exception in your mind only for arrays.
这只是您在脑海中为数组设置的例外。
So is it better to be "more correct" or "more uniform" in this case?
那么在这种情况下是“更正确”还是“更统一”更好?
回答by Joe
In many cases where a one-dimensional array is used, it's essentially being used as a fixed-size list.
在许多使用一维数组的情况下,它本质上是用作固定大小的列表。
Personally I will often declare an array as IList<T>, and use the Count property rather than Length:
我个人经常将数组声明为 IList<T>,并使用 Count 属性而不是 Length:
IList<string> strings = new string[] { ...};
Another useful member of IList<T> that does not exist in Array is the Contains() method.
Array 中不存在的 IList<T> 的另一个有用成员是 Contains() 方法。
回答by elder_george
If you're using C# 3.0, you may use Enumerable.Count() extension method that works on all IEnumerable implementations, including lists, arrays and dictionaries.
如果您使用的是 C# 3.0,则可以使用 Enumerable.Count() 扩展方法,该方法适用于所有 IEnumerable 实现,包括列表、数组和字典。
It causes some overhead, but it's usually tolerable.
这会导致一些开销,但通常是可以容忍的。