やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

C#の概念 インデクサ

 [0],["key"]のようにアクセスするヤツ。

成果物

コード

 以下のように宣言する。[]にはインデクサのキーとなる型と変数名を書く。

public int this[string key] {
    get {  }
    set {  }
}

 以下のようにクラス内で定義する。

class NamedNumber {
    Dictionary<string, int> dict;
    public NamedNumber() {
        dict = new Dictionary<string, int>() {
            ["A"] = 0,
            ["B"] = 1,
        };
    }
    public int this[string key] {
        get { return dict[key]; }
        set { dict[key] = value; }
    }
}

 呼出してみる。

class Main {
    public void Run() {
        var n = new NamedNumber();
        Console.WriteLine($"{n["A"]}, {n["B"]}");
        n["A"] = 9;
        Console.WriteLine($"{n["A"]}, {n["B"]}");
    }
}
0, 1
9, 1

 getsetができた。

多次元

 インデクサの要素を複数にしたいならカンマ区切りにする。this[int key1, int key2]のように。instance[0, 0]でアクセスできる。

using System;
using System.Collections.Generic;

namespace Concept.Indexer.Lesson1 {
    class Main {
        public void Run() {
            var n = new MappedNumber();
            Console.WriteLine($"{n[0,0]}");
            n[0,0] = 9;
            Console.WriteLine($"{n[0,0]}");
        }
    }
    class MappedNumber {
        int[,] nums;
        public MappedNumber() {
            nums = new int[2,2] {
                { 0, 1 }, { 2, 3 }
            };
        }
        public int this[int a, int b] {
            get { return nums[a,b]; }
            set { nums[a,b] = value; }
        }
    }
}

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux