C#中索引器的操作

iamzxf發表於2015-03-18


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace indexDemo
{
    class SampleIndex
    {
        private double[] arr = new double[5] { 1, 2, 3, 4, 5 };

        public double this[int index]
        {
            get 
            {
                if (index < 0 || index >= 5)
                {
                    return 0;
                }
                else
                {
                    return arr[index];
                }
            }
            set 
            {
                if (index >= 0 || index < 5)
                {
                    arr[index] = value;
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            SampleIndex smp = new SampleIndex();
            smp[3] = 7.4;
            smp[2] = 8.9;

            for (int i = 0; i < 6; i++)
                Console.WriteLine(smp[i]);

            Console.ReadLine();
        }
    }
}



相關文章