What is the meaning of “this [int index]”?

后端 未结 2 1501
逝去的感伤
逝去的感伤 2021-01-17 16:00

In C# we have the following interface:

public interface IList : ICollection, IEnumerable, IEnumerable
{
    T this [int index] { g         


        
2条回答
  •  借酒劲吻你
    2021-01-17 16:33

    That is an indexer defined on the interface. It means you can get and set the value of list[index] for any IList list and int index.

    Documentation: Indexers in Interfaces (C# Programming Guide)

    Consider the IReadOnlyList interface:

    public interface IReadOnlyList : IReadOnlyCollection, 
        IEnumerable, IEnumerable
    {
        int Count { get; }
        T this[int index] { get; }
    }
    

    And an example implementation of that interface:

    public class Range : IReadOnlyList
    {
        public int Start { get; private set; }
        public int Count { get; private set; }
        public int this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                {
                    throw new IndexOutOfBoundsException("index");
                }
                return Start + index;
            }
        }
        public Range(int start, int count)
        {
            this.Start = start;
            this.Count = count;
        }
        public IEnumerable GetEnumerator()
        {
            return Enumerable.Range(Start, Count);
        }
        ...
    }
    

    Now you could write code like this:

    IReadOnlyList list = new Range(5, 3);
    int value = list[1]; // value = 6
    

提交回复
热议问题