首页 > 其他 > 详细

索引器

时间:2017-09-30 16:57:39      阅读:243      评论:0      收藏:0      [点我收藏+]
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 索引
{
    class Program
    {
        static void Main(string[] args)
        {
            Person per = new Person();
            //per.Numbers = new int[] { 1, 2, 3, 4, 5 };

            //for(int i =0; i < per.Numbers.Length;i++)
            //{
            //    Console.WriteLine(per.Numbers[i]);
            //}

            //以索引方式访问
            per[0] = 2;
            per[1] = 3;
            per["Mao"] = "good";
            per["Dog"] = "bad";
            for (int i = 0; i < per.Numbers.Length; i++)
            {
                Console.WriteLine(per[i]);
            }

            Console.WriteLine(per["Mao"]);
            Console.ReadKey();

            

        }
    }

    class Person
    {
        private int[] numbers = new int[5];

        public int[] Numbers
        {
            get
            {
                return numbers;
            }
            set
            {
                numbers = value;
            }
        }

        //创建索引器,让对象以索引的方式操作数组
        public int this[int index]
        {
            get
            {
                return numbers[index];
            }

            set
            {
                numbers[index] = value;
            }
        }

        //键值对,前面是键,后面是值
        Dictionary<string, string> dic = new Dictionary<string, string>();
        public string this[string index]
        {
            get
            {
                return dic[index];
            }

            set
            {

                dic[index]= value;
            }
        }

        Dictionary<int, string> dic2 = new Dictionary<int, string>();

        //public string this[int index] { }
        //与public int this[int index]只有返回值不一样,不能重载
    }
}

  

索引器

原文:http://www.cnblogs.com/my-cat/p/7615245.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!