简体   繁体   中英

Basic C# class question regarding the “this” keyword

I'm going through someone else's code and I saw this statement:

public CustomClassName this [ string varName]

Please excuse the newbness of this question, but the square brackets threw me off. Is this a method or constructor?

How does the "this" variable work in this case?

It's called an indexer. MSDN page.

它是一个索引器,因此您可以访问类似于数组的类。

It is defining an index operator on your type. Take for example, the List<T> class. The library designers wanted you to be able to write code like this:

List<int> list = new List<int> { 1, 2, 3, 4, 5 };
int x = list[2]; // x == 3

The syntax that accomplishes that is what you have posted above. So, for your own types, you can...

class NameCollection : /* whatever */
{
    private List<string> _names = new List<string> { "Ed", "Sally", "John" };

    public string this[int index]
    {
        get { return _names[index]; }
    }
}

this is simply an overload of the square-bracket operator in C#.

see here:

How do I overload the square-bracket operator in C#?

Neither, it's an Indexer . It allows you to do CustomClassName[ obj ] and retrieve a value from the object.

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