zoukankan      html  css  js  c++  java
  • 索引器

     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]只有返回值不一样,不能重载
        }
    }
    

      

  • 相关阅读:
    CSP-S2-2019游记
    【BZOJ2301】【HAOI2011】Problem B
    【NOIp2017】宝藏
    【NOIp2016】天天爱跑步
    【NOIp2018】保卫王国
    【BZOJ2159】Crash的文明世界
    Van爆零赛总结
    【ZJOI2016】小星星
    【CF1025D】Recovering BST
    【HAOI2016】字符合并
  • 原文地址:https://www.cnblogs.com/my-cat/p/7615245.html
Copyright © 2011-2022 走看看