码迷,mamicode.com
首页 > 编程语言 > 详细

C#语言的索引器

时间:2015-05-07 07:35:19      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
       
        static void Main(string[] args)
        {
            var names = new IndexedNames();
            names[0] = "hello";
            names[1] = "hong";
            names[2] = "qian";
            names[3] = "jin";
            names[4] = "name";
            names[5] = "hao";
            names[6] = "good";
            for (int i = 0; i <= 6; i++)
            {
                Console.WriteLine(names[i]);
            }
            Console.WriteLine(names["jin"]);
            Console.WriteLine(names["aaaa"]);
                Console.ReadKey();
        }
     
    }
    class IndexedNames
    { 
        private string [] nameList=new string [10];
        public IndexedNames()
        {
            for (int i = 0; i < nameList.Length; i++)
            {
                nameList[i] = "N/A";
            }
        }
        public string this[int index]
        {
            get
            {
                string tmp;
                if (index > 0 && index <= nameList.Length - 1)
                {
                    tmp = nameList[index];
                }
                else
                {
                    tmp = "";
                }
                return tmp;
            }
            set
            {
                if (index > 0 && index <= nameList.Length - 1)
                {
                    nameList[index] = value;
                }
            }
        }

        public int this[string name]
        {
            get
            {
                int index = 0;
                while (index < nameList.Length)
                {
                    if (nameList[index] == name)
                    {
                        return index;
                    }
                    index++;
                 }
                return -1;
            }
        }
    }
    public interface ISomeInterface
    {
        int this[int index]
        {
            get;
            set;
        }
    }
    class IndexerClass : ISomeInterface
    { 
        private int[] arr=new int [100];
        public int this[int index]
        {
            get
            {
                return arr[index];

            }
            private set
            {
                arr[index] = value;
            }
         }
    }
}

 

C#语言的索引器

标签:

原文地址:http://www.cnblogs.com/heisaijuzhen/p/4483769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!