Другие языки программирования и технологии

Подскажи по-быстрому, есть ли разница в юзании [ ] и ElementAt() у List<> в C#? Если есть, то какая?

NA
Nursultan Aitmaganbetov
3 999
Почувствуйте разницу:

// System.Linq.Enumerable
public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    IList<TSource> list = source as IList<TSource>;
    if (list != null)
    {
        return list[index];
    }
    if (index < 0)
    {
        throw Error.ArgumentOutOfRange("index");
    }
    TSource current;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            if (index == 0)
            {
                current = enumerator.Current;
                return current;
            }
            index--;
        }
        throw Error.ArgumentOutOfRange("index");
    }
    return current;
}

----------------------------------------------------------------------------
// System.Collections.Generic.List<T>
public T this[int index]
{
    [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    get
    {
        if (index >= this._size)
        {
            ThrowHelper.ThrowArgumentOutOfRangeException();
        }
        return this._items[index];
    }
    [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    set
    {
        if (index >= this._size)
        {
            ThrowHelper.ThrowArgumentOutOfRangeException();
        }
        this._items[index] = value;
        this._version++;
    }
}
Заур Рамизович
Заур Рамизович
62 732
Лучший ответ
у листа тоже индексатор есть как бы)
Руслан Ляпун
Руслан Ляпун
1 816