0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】【文法】インデクサ

Posted at

インデクサはプロパティの配列版で、
配列への参照,アクセスした際の挙動を特殊なメソッドに定義できる。


    // インデクサ
    class Practice8_2
    {
        static void Main(string[] args)
        {
            // プロパティを介してprivateな変数にアクセスできる。
            Sample s = new Sample();
            s.Param1 = 10;
            int n = s.Param1;

            FreeArray array = new FreeArray(10);
            array[3] = 10;
        }
    }

    class FreeArray
    {

        // プロパティの配列版
        // 配列にアクセスした際の挙動を決める。
        private int[] _list;
        public int this[int index]
        {
            set
            {
                this._list[this.GetIndex(index)] = value;
            }
            get
            {
                return this._list[this.GetIndex(index)];
            }
        }

        public FreeArray(int size)
        {
            this._list = new int[size];
        }

        // 引数で渡したインデックスの次のインデックスを返却する。
        private int GetIndex(int index)
        {
            return ++index;
        }
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?