zoukankan      html  css  js  c++  java
  • C# 索引器(C#学习笔记05)

    索引器

    1. 索引器能够使对象像数组一样被索引,使用数组的访问方式 object[x]
    2. 索引器的声明在某种程度上类似于属性的声明,例如,使用 get 和 set 方法来定义一个索引器。
    3. 不同的是,属性值的定义要求返回或设置一个特定的数据成员,而索引器的定义要求返回或设置的是某个对象实例的一个值,即索引器将实例数据切分成许多部分,然后通过一些方法去索引、获取或是设置每个部分。
    4. 定义属性需要提供属性名,而定义索引器需要提供一个指向对象实例的 this 关键字。
    5. 索引可以重载

    使用索引示例:

    using System;
    namespace IndexerApplication
    {
        class indexC
        {
            public static int number = 10;
            private string[] str = new string[number];
            public indexC()
            {
                for(int i = 0; i < number; i++)
                {
                    str[i] = "null";
                }
            }
            public string this[int index]   //创建索引,int为索引的类型
            {
                set
                {
                    if (index >= 0 && index < 10)
                    {
                        str[index] = value; //value为传入字符串
                    }
                }
                get
                {
                    string temp="";
                    if (index >= 0 && index < 10)
                    {
                        temp = str[index];
                    }
                    return temp;
                }
            }
            static void Main()
            {
                indexC I = new indexC();
                I[0] = "zero";
                I[1] = "one";
                I[2] = "two";
                for(int i = 0; i < indexC.number; i++)
                {
                    Console.WriteLine(I[i]);
                }
            }
        }
    }

    运行:

    zero
    one
    two
    null
    null
    null
    null
    null
    null
    null
    C:Program Filesdotnetdotnet.exe (进程 5248)已退出,返回代码为: 0。
    若要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
    按任意键关闭此窗口...

    参考链接:https://www.w3cschool.cn/wkcsharp/sozt1nvr.html
  • 相关阅读:
    CSP 201612-3 权限查询 【模拟+STL】
    Vijos 1565 多边形 【区间DP】
    制作进度条(UISlider)
    制作按钮(Button)
    制作UI纹理(UI Texture)
    制作标签(Label)
    什么是UI控件
    制作精灵(UI Sprite)
    深度(Depth)概念
    2D UI和3D UI的工作原理
  • 原文地址:https://www.cnblogs.com/asahiLikka/p/11657081.html
Copyright © 2011-2022 走看看