索引器

索引

没有名字 ,索引器的内部本质(ILSpy的IL模式下看)类型this[参数]{get;set;}

可以是只读或者只写(在get或者set前加上private)

字符串是只读索引,因此不能对字符串中的某个字符进行从新赋值,即只能char ch = s[5];不能s[5]=‘a’。

开发中自己写的机会很少,一道面试题:C#中索引器是否只能根据数字进行索引?是否允许多个索引器参数?答案:可以进行非数字索引,可以允许多个参数进行索引

using System;

usingSystem.Collections;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;


namespaceTestConsole

{

   class Program

   {

        static void Main(string[] args)

        {

            MyIntIndex myIntIndex = newTestConsole.MyIntIndex();//整型索引

            stringname1 = myIntIndex[1];

            Console.WriteLine(name1);

            Hashtable ht = new Hashtable();

            ht.Add("001", "chizi");

            ht.Add("002", "dandan");

            MyStringIndex myStringIndex = newTestConsole.MyStringIndex(ht);//字符串索引

            string name2 = myStringIndex["001"];

            Console.WriteLine(name2);

            Console.ReadKey();

        }

   }

   class MyStringIndex

   {

        private Hashtable ht;//字符串索引用到哈希表来存放键值对

        public MyStringIndex(Hashtableht)

        {

            this.ht = ht;

        }

        public string this[stringkey]

        {

            get

            {

                string name =(string)ht[key];

                returnname;

            }

            set

            {

                ht[key] =value;

            }

        }

   }

   class MyIntIndex

   {

        private static string[] name = { "dandan", "chizi", "jianguo"};

        public string this[intindex]

        {

            get

            {

                stringn = name[index];

                returnn;

            }

            set

            {

                name[index] =value;

            }

        }

   }

}���N%k1}�� �?�[��89

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容