为什么 C# 数组没有 Count 属性?
可能的重复:
集合中的计数、长度与大小
真的很奇怪:
C#如下所示的数组
double[] test = new double[1];
支持 Length 属性来获取数组的大小。但数组还实现了 IList 接口:
IList<double> list = test;
但是,IList 接口还提供了 Count 属性。为什么数组(在本例中为“测试”)没有?
编辑:感谢大家指出,实际上是 ICollection 接口(而不是 IList)提供了 Count 属性,而且这是由于该接口的显式实现所致。
Possible Duplicate:
count vs length vs size in a collection
Really strange:
C# arrays such as the following
double[] test = new double[1];
support the Length property to get the size of the array. But arrays also implement an IList interface:
IList<double> list = test;
However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?
Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单地说,他们选择将其称为
Length
,并通过显式接口实现来实现Count
- 类似于:Simply, they chose to call it
Length
, and implementCount
via explicit interface implementation -something like:这是关于命名的设计选择,而不是语义。
数组具有 Length 属性,字符串也是如此。
长度信号不可变:您不能添加到数组或从数组中删除。
列表和其他容器具有通常可以更改的 Count 属性。
哦,如果您调用
list.Append(1.1);
您将收到不支持的异常。It was a design choice about Naming, not semantics.
Arrays have a Length property, as does the String.
Length signals immutable: You cannot Add to or Remove from an array.
Lists and other containers have a Count property that can usually change.
Oh, and if you call
list.Append(1.1);
you will get a not supported exception.Count
属性使用显式接口声明样式隐藏,例如在类定义中:您可以使用类型转换访问像这样隐藏的方法和属性,例如
The
Count
property is hidden using the explicit interface declaration style, for example like this in a class definition:You can access methods and properties hidden like this using a type cast, e.g.
继承自
Array
的类型获取的实现>IList
在运行时(这是怎么可能的,不要问我):实际上,
IList
实现的行为类似于 显式实现,如 Marc 解释的 在他的回答中。这就是为什么您可以从强制转换的结果访问IList
的某些成员,但不能从专门键入为T[]
的变量访问。Types inheriting from
Array
obtain implementations ofIList<T>
at run-time (how this is possible, don't ask me):In effect the
IList<T>
implementation acts like an explicit implementation, as Marc explained in his answer. This is why you can access certain members ofIList<T>
from the result of a cast but not from a variable typed asT[]
specifically.