简体   繁体   English

在 C# 中的 class 上实现索引“运算符”

[英]Implementing indexing “operator” in on a class in C#

How would one go about implementing the indexing "operator" on a class in C#? go 如何在 C# 中的 class 上实现索引“运算符”?

class Foo {

}

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

in C#?在 C# 中? Searched MSDN but came up empty.搜索了 MSDN,但空无一物。

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.如果需要,您可以为不同类型定义多个访问器(例如,字符串而不是 int)。

There called Indexers or sometimes Indexer Properties.有称为索引器或有时索引器属性。

Here's the MSDN page about them.这是关于它们的MSDN页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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