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

  • 相关阅读:
    python基础学习8(浅拷贝与深拷贝)
    适配器模式(Adapter)
    NHibernate的调试技巧和Log4Net配置
    查看表字段的相关的系统信息
    Asp.net MVC 3 开发一个简单的企业网站系统
    ie8 自动设置 兼容性 代码
    同时安装vs2010和VS2012后IEnumerable<ModelClientValidationRule>编译错误
    各种合同样本
    使用远程桌面的朋友可能经常会遇到“超出最大允许连接数”的问题,
    弹出窗口全屏显示:window.showModalDialog与window.open全屏显示
  • 原文地址:https://www.cnblogs.com/wuyisky/p/854013.html
Copyright © 2011-2022 走看看