天天看點

C#程式設計-98:索引器在接口中的使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace InterfaceTest
{
    public interface IIndexTest
    {
        int this[int index]
        {
            set;
            get;
        }
    }
    class Indextest : IIndexTest
    { 
    private int[] myint=new int[10];
    public int this[int index]
    {
        set
        {
            if (index >= 0 && index < 10) 
                myint[index] = value;
        }
        get
        {
            if (index < 0 || index >= 10)
                return 0;
            else
                return myint[index];
        }
    }
         
    }
    class Program
    {
        static void Main(string[] args)
        {
            Indextest arr = new Indextest();
            arr[-1] = 5;
            arr[4] = 10;
            arr[9] = 15;
            arr[14] = 20;
 
            for (int i = -1; i < 15; i = i + 5)
            {
                Console.WriteLine("arr[{0}]={1}",i,arr[i]);
            }
            Console.ReadKey();
        }
    }
}      
C#程式設計-98:索引器在接口中的使用
C#程式設計-98:索引器在接口中的使用