简体   繁体   中英

Implementing indexing “operator” in on a class in C#

How would one go about implementing the indexing "operator" on a class in C#?

class Foo {

}

Foo f = new Foo();
f["key"] = "some val";
f["other key"] = "some other val";

in C#? Searched MSDN but came up empty.

Here is an example using a dictionary as storage:

public class Foo {

    private Dictionary<string, string> _items;

    public Foo() {
        _items = new Dictionary<string, string>();
    }

    public string this[string key] {
        get {
            return _items[key];
        }
        set {
            _items[key]=value;
        }
    }

}
    private List<string> MyList = new List<string>();
    public string this[int i]
    {
        get
        {
            return MyList[i];
        }
        set
        {
            MyList[i] = value;
        }

    }

You can define several accessors for different types (ie string instead of int for example) if it's needed.

There called Indexers or sometimes Indexer Properties.

Here's the MSDN page about them.

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