在评论中,it说
如果源类型实现IList,则该实现用于获取指定索引处的元素。否则,此方法获取指定的元素。
String未实施IList<T>
。这是否意味着如果我声明像
O(n)
操作
IEnumerable<char> myString = "stringy";
答案 0 :(得分:7)
ElementAt
的类型时, string
将是O(N)操作。它没有实现IList<char>
,因此ElementAt
不会对它进行任何优化,而是通过IEnumerable<char>
进行枚举,直到达到指定的索引。
答案 1 :(得分:1)
由于字符串未实现IList
,但IEnumerable<char>
ElementAt将执行以下代码:
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
和字符串上的GetEnumerator检索CharEnumerator
,这是你假设的O(n)。
如果您想要更好的实现,请创建自己的扩展方法
public static class StringExt
{
public static char ElementAt(this string input, int index)
{
if (index < input.Length) return input[index];
throw new IndexOutOfRangeException();
}
}
我假设是O(1),但很难说,因为字符串上的索引访问器是在不安全的代码中完成的。