如何为 C# 泛型集合获取一致的 .Count / .Length 属性?
List
具有 .Count
属性,而 T<>
数组则为 .Length
。我认为这是因为数组是固定长度的,而其他数组不是,但语法上的差异仍然令人沮丧。
如果您从数组重构为列表,它会给出“不包含 .Length 的定义”错误,并且在 .Count
和 时更改它似乎是浪费时间。长度本质上是相同的。
有没有好的办法来处理这个问题呢?是否可以扩展 List
以添加 .Length
属性(例如,.Count
的别名),反之亦然通用数组?出于某种原因,这会是一个坏主意吗?
List<T>
has the .Count
property, where as T<>
arrays .Length
instead. I presume this is because arrays are fixed-length whereas the others aren't, but the difference in syntax can still be frustrating.
If you refactor from an array to list, it therefore gives "does not contain a definition for .Length" errors, and it seems a waste of time having to change it when .Count
and .Length
are essentially the same.
Is it there a good way to deal with this ? Is it possible to extend List<T>
to add an .Length
property that's an alias for .Count
for instance, and vice-versa for the generic array ? And would this be a bad idea for any reason ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
Count
LINQ。经过优化,可以使用等都将被优化。
Count
属性由ICollection
界面提供尽可能(或非通用ICollection
.NET 4 中也有接口)。因此数组、List或者,如果您想要某种一致的计数属性,而又不想冒在非优化情况下迭代整个序列的风险,那么您可以创建自己的扩展方法。 (我个人不会走这条路。)
You can use the
Count
method provided by LINQ.This is optimised to use the
Count
property provided by theICollection<T>
interface where possible (or the non-genericICollection
interface too in .NET 4). So arrays,List<T>
etc will all be optimised.Alternatively, if you wanted a consistent count property of some kind without running the risk of iterating an entire sequence in the non-optimised case then you could create your own extension methods. (I personally wouldn't go down this route.)
您可以将数组放入
IList
类型的变量中。 (数组实现此接口)然后,您可以像使用任何其他
IList
一样使用该数组(尽管Add
和Remove
将抛出异常,因为数组是固定长度的)You could put your array in a variable of type
IList<T>
. (arrays implement this interface)You can then use the array exactly the way you use any other
IList<T>
(althoughAdd
andRemove
will throw exceptions, since arrays are fixed-length)您可以对列表和数组使用
.Count()
方法。.Count()
方法在可用时运行,然后返回到传统的.Length
。You can use the
.Count()
method for both List and Arrays.The
.Count()
method runs if it is available, then it falls back to the traditional.Length
.您可以简单地扩展通用列表并添加计数方法,但是如果这样做的原因仅仅是因为您的重构并且不想更新为计数,我不建议这样做。如果您没有真正向类添加任何内容,则无需扩展该类。为什么不直接更新代码以使用计数而不是长度呢?
You could simply extend the generic List and add a count method, however if the reason for this is simply because your re-factoring and don't want to update to Count, I don't advise doing so. No need to extend a class if you're not really adding anything to it. Why not just update your code to use Count instead of Length?