简体   繁体   中英

What does “this[0]” mean in C#?

I was going through some library code and saw a method like:

public CollapsingRecordNodeItemList List
{
    get { return this[0] as CollapsingRecordNodeItemList; }
}

The class that contains this method is not a list or something iterable, so what exactly does this[0] mean?

Look for an indexer in the class.

C# lets you define indexers to allow this sort of access.

Here is an example from the official guide for "SampleCollection".

public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets 
            // the corresponding element from the internal array. 
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }

Here is the definition from the official language specification :

An indexer is a member that enables objects to be indexed in the same way as an array. An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimiters [ and ]. The parameters are available in the accessor(s) of the indexer. Similar to properties, indexers can be read-write, read-only, and write-only, and the accessor(s) of an indexer can be virtual.

One can find the full and complete definition in section 10.9 Indexers of the specification.

It means that the declaring type (or a base-class of that) has an "indexer" which presumably takes an int (or similar) and returns... something (perhaps object ?). The code calls the indexer's get accessor, passing 0 as the index - and then treats the returned value as a CollapsingRecordNodeItemList (or null the returned value isn't compatible with that).

For example:

public object this[int index] {
    get { return someOtherList[index]; }
}

Easiest thing to do is the step into it, though. That will tell you exactly where it is going.

Assuming the class itself inherits from some form if IList / IList<T> , it's just returning (and casting) the first element in the collection.

public class BarCollection : System.Collections.CollectionBase
{
    public Bar FirstItem
    {
        get { return this[0] as Bar; }
    }

    #region Coming From CollectionBase
    public Object this[ int index ]  {
        get { return this.InnerList[index]; }
        set { this.InnerList[index] = value; }
    }
    #endregion
}

It means to invoke the item property's get method on this class. It's called the class's Indexer

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM