C#基礎增強(1)之索引器

索引器

介紹

索引器,初學者可能聽起來有些陌生,但其實咱們常常會用到它,例如:面試

// 字符串的索引器
string str = "hello world";
char c = str[4]; // 獲取到字符串中索引爲 4 的字符

// 字典的索引器
var info = new Dictionary<string,string>();
info.Add("name1","張三");
// 從字典中經過索引器獲取到 key 爲 name1 的值
string name1 = info["name1"];

索引器的建立

看以下實體類:this

public class Person
{
    private string _value;
    // 索引器
    public string this[int i, int j]
    {
        get
        {
            Console.WriteLine(i + "" + j + " from get");
            return _value;
        }
        set
        {
            Console.WriteLine(i + "" + j + " from set");
            this._value = value;
        }
    }
}

在該類中建立了一個索引器,能夠經過索引器對 Person 類中的 hobbies 字段進行操做,以下:spa

var person = new Person();
// 給 person 對象中的 hobbies 列表屬性前三個索引位置插入數據
person[0,0] = "吃飯";
person[1,0] = "睡覺";
person[2,0] = "打豆豆";
person.Hobbies.ForEach(h => { Console.WriteLine(h); });
/*
吃飯
睡覺
打豆豆
 */

// 獲取 hobbies 列表屬性前兩個元素
var hobbyStr = person[0,2];
Console.WriteLine(hobbyStr);
/*
吃飯,睡覺
 */

相關面試題

一、爲何字符串只能 char c = s[5]; ,而不能 s[5] = 'a'; ?code

由於字符串類的索引只讀,以下:對象

[__DynamicallyInvokable]
[IndexerName("Chars")]
public extern char this[int index] { [SecuritySafeCritical, __DynamicallyInvokable, MethodImpl(MethodImplOptions.InternalCall)] get; }

二、C# 中索引器是否是隻能根據數字索引?是否容許多個索引器參數?blog

  • 不是隻能根據數字索引,例如上面介紹示例中的字典就能夠使用字符串。
  • 容許多個索引器參數,如上面的 Person 類。
相關文章
相關標籤/搜索