zoukankan      html  css  js  c++  java
  • C#高级编程索引器

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

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

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

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

    using System;

    using System.Collections;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    namespace TestConsole

    {

        class Program

        {

            static void Main(string[] args)

            {

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

                string name1 = myIntIndex[1];

                Console.WriteLine(name1);

                Hashtable ht = new Hashtable();

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

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

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

                string name2 = myStringIndex["001"];

                Console.WriteLine(name2);

                Console.ReadKey();

            }

        }

        class MyStringIndex

        {

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

            public MyStringIndex(Hashtable ht)

            {

                this.ht = ht;

            }

            public string this[string key]

            {

                get

                {

                    string name =(string)ht[key];

                    return name;

                }

                set

                {

                    ht[key] = value;

                }

            }

        }

        class MyIntIndex

        {

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

            public string this[int index]

            {

                get

                {

                    string n = name[index];

                    return n;

                }

                set

                {

                    name[index] = value;

                }

            }

        }

    }

     

  • 相关阅读:
    JAVA编程-------29、求3*3矩阵对角线元素之和
    JAVA编程---------28、对10个数进行排序(冒泡排序)
    JAVA编程-------------27、100以内的素数
    JAVA编程----------26、请输入星期几的第一个字母来判断一下星期几, 第一个字母相同,则判断第二个字母,以此类推
    JAVA编程-----------25、查找5位数的回文数
    JAVA编程---------24、输入一个数,判断位数,并逆序输出
    JAVA编程------------23、递归
    JAVA编程------------22、利用递归求5!
    JAVA编程--------21、求1!+2!+....+20!=
    JAVA编程------------20、计算2/1+3/2+5/3+8/5+...求前20项之和
  • 原文地址:https://www.cnblogs.com/qiu18359243869/p/13049927.html
Copyright © 2011-2022 走看看