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


    经常见有这样的类:如aClass a = new Class();然后在程序里出现个a[i]="some string";感觉好奇怪:既然没有声明类数组却用[]索引,而且返回个string类型,在msdn2和google、baidu同学的帮助之下终于弄明白原来是c#的索引器,弄明白了原理之后自己写了个小示例程序。声明:程序完全自主编写,只要对大家有帮助,随便拷贝: )

    using System ;
    /// <summary>
    /// 索引器示例
    /// </summary>

    class StringCollection  //建立一个字符串容器类
    {
        readonly int _count;
        string[] str;
        public StringCollection(int count)
        {
            if (count > 1)
            {
                _count = count;
                str = new string[_count];
            }
        }
        public string this[int index]   //索引器
        {
            get
            {
                if (index >= 0 && index < _count)
                    return str[index];
                else
                    return "error index!";
            }
            set
            {
                if (index < 0 || index >= _count)
                    throw new Exception("Out of Range!");
                else
                    str[index] = value;
            }
        }
        static void Main()
        {
            StringCollection test = new StringCollection(5);
            test[0] = "Hello Word!";
            test[2] = "Hi China!";
            test[4] = "How do you do!";
            for (int i = 0; i < 6; i++)
                Console.WriteLine("String #{0} = {1}", i, test[i]);

            StringCollection[] a = new StringCollection[3]; //定义一个3维StringCollection
            for (int i =0;i<3;i++)
                for (int j = 0; j < 2; j++)
                {
                    a[i] = new StringCollection(2); //对每一个StringCollection调用构造函数
                    a[i][j] = i.ToString() + j.ToString();
                    Console.WriteLine(a[i][j]);
                }
            Console.Read();
        }
    }

  • 相关阅读:
    ARM-Linux S5PV210 UART驱动(1)----用户手册中的硬件知识
    可变参数列表---以dbg()为例
    《C和指针》 读书笔记 -- 第7章 函数
    《Visual C++ 程序设计》读书笔记 ----第8章 指针和引用
    支持异步通知的globalfifo平台设备驱动程序及其测试代码
    linux内核中sys_poll()的简化分析
    《C和指针》读书笔记——第五章 操作符和表达式
    测试方法-等价类划分法
    MonkyTalk学习-8-Agent
    MonkyTalk学习-7-Verify-Verify
  • 原文地址:https://www.cnblogs.com/wuyisky/p/854013.html
Copyright © 2011-2022 走看看