簡體   English   中英

在 C# 中的 class 上實現索引“運算符”

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

go 如何在 C# 中的 class 上實現索引“運算符”?

class Foo {

}

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

在 C# 中? 搜索了 MSDN,但空無一物。

這是一個使用字典作為存儲的示例:

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;
        }

    }

如果需要,您可以為不同類型定義多個訪問器(例如,字符串而不是 int)。

有稱為索引器或有時索引器屬性。

這是關於它們的MSDN頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM