为什么要使用Enumerable.ElementAt()与[]操作? [英] Why would I use Enumerable.ElementAt() versus the [] operator?

查看:563
本文介绍了为什么要使用Enumerable.ElementAt()与[]操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个愚蠢的问题,但我还没有找到答案,所以在这儿呢。 :)

在这两种情况下,你会如果你没有检查你收藏的界限得到一个超出范围的异常。这只是编码风格preference?

和万一有人需要一个例子:

 列表<位> myList中=新名单<位>(){0×01,0×02,×03};
字节testByte = myList.ElementAt(2);

 字节testByte = myList中[2];


解决方案

由于可枚举是比较通用的,并且通过枚举psented集合再$ P $可能没有一个索引器。

但是,如果这样做 - 不使用的ElementAt()它可能不会被视为有效

This seems like a silly question, but I haven't found the answer, so here it is. :)

In both cases, you will get an "out-of-range" exception if you fail to check the bounds of your collection. Is this just coding style preference?

And in case someone needs an example:

List<byte> myList = new List<byte>(){0x01, 0x02, 0x03};
byte testByte = myList.ElementAt(2);

versus

byte testByte = myList[2];

解决方案

Because Enumerable is more generic, and a collection represented by enumerable may not have an indexer.

But, if it does - don't use ElementAt() it's probably not going to be as efficient.

这篇关于为什么要使用Enumerable.ElementAt()与[]操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆