C#索引器使用

来源:互联网 发布:定制家具效果图软件 编辑:程序博客网 时间:2024/04/30 03:52

索引器

索引器用于封装内部集合或数组。
索引器在语法上方便了程序员将类、结构或接口作为数组进行访问。
要声明类或结构上的索引器,需要使用this关键字。
例如:
public int this[int index]    // 索引器声明
{
  // get and set accessors
}

//////////////////////////////////////////////////////////////////////////
//索引器使用
using System;
namespace IndexExample{
    class DayCollection {
        string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
        public int this[string day] {
            get {
                return (GetDay(day));
            }
        }
        public string this[int i] {
            get {
                return (days[i]);
            }
        }
        private int GetDay(string testDay)
        {
            int i = 0;
            foreach (string day in days)
            {
                if (day == testDay)
                {
                    return i;
                }
                i++;
            }
            return -1;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DayCollection week = new DayCollection();
            Console.WriteLine(week[1]);
            Console.WriteLine(week["Fri"]);
            Console.WriteLine(week["Other Day"]);
            Console.ReadLine();
        }
    }
}

原创粉丝点击