アットウィキロゴ

インデクサ

インスタンス内でデータを配列のように使用できる

データ配列と異なり、定義するインスタンスは1つのみ

サンプル

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication35
{
    class Program
    {
        static void Main(string[] args)
        {
            Test2 a = new Test2();
            a[0] = 10;
            a[1] = 210;
            a[2] = 310;
            a[3] = 410;
            a[4] = 510;
 
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("a[{0}]={1}", i, a[i]);
            }
 
            Console.ReadKey();
 
        }
    }
 
    class Test2
    {
        private int[] data = new int[5];
 
        // インデクサを使用する場合はthisを指定
        public int this[int i]
        {
            get
            {
                return this.data[i];
            }
            set
            {
                this.data[i] = value;
            }
        }
 
 
    }
}
 
 
 
コンストラクタを使用して配列の数を制限することも可能
配列なので1次元、2次元配列なども使用可能

※使いどころの判定が難しい




最終更新:2011年04月10日 11:28