索引器C#

Code:

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

namespace ConsoleApp2010Thisindexer
{
    // Using a string as an indexer value
    public class DayCollection
    {
        string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };

        // This method finds the day or returns -1
        private int GetDay(string testDay)
        {
            int i = 0;
            foreach (string day in days)
            {
                if (day == testDay)
                {
                    return i;
                }
                i++;
            }
            return -1;
        }

        // The get accessor returns an integer for a given string
        public int this[string day]
        {
            get
            {
                return (GetDay(day));
            }
        }

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

namespace ConsoleApp2010Thisindexer
{
    public class IndexerClass
    {
        private int[] arr = new int[100];
        // Indexer declaration
        public int this[int index]
        {
            get
            {
                //Check the index limits.
                if (index < 0 || index >= 100)
                {
                    return 0;
                }
                else
                {
                    return arr[index];
                }
            }
            set
            {
                if (!(index < 0 || index >= 100))
                {
                    arr[index] = value;
                }
            }

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

namespace ConsoleApp2010Thisindexer
{
    class Program
    {
        static void Main(string[] args)
        {

            IndexerClass test = new IndexerClass();
            // Call the indexer to initialize the elements #3 and #5.
            test[3] = 256;
            test[5] = 1024;
            for (int i = 0; i <= 10; i++)
            {
                System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
            }

            DayCollection week = new DayCollection();
            System.Console.WriteLine(week["Fri"]);
            System.Console.WriteLine(week["Made-up Day"]);


        }
    }
}

原文地址:https://www.cnblogs.com/Leo_wl/p/1807409.html