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();
        }
    }

  • 相关阅读:
    net中System.Security.Cryptography 命名空间 下的加密算法
    关于如何生成代码的帮助文档的链接
    Application.EnableVisualStyles();
    VS2010里属性窗口中的生成操作
    把普通的git库变成bare库
    MultiTouch camera controls source code
    android onTouch()与onTouchEvent()的区别
    iOS开发中常见的语句@synthesize obj = _obj 的意义详解
    java nio 快速read大文件
    使用ndk standalone工具链来编译某个平台下的库
  • 原文地址:https://www.cnblogs.com/wuyisky/p/854013.html
Copyright © 2011-2022 走看看