• 【C#】索引器


    索引器允许类或者结构的实例按照与数组相同的方式进行索引取值,索引器与属性类似,不同的是索引器的访问是带参的。

    索引器和数组比较:

    (1)索引器的索引值(Index)类型不受限制

    (2)索引器允许重载

    (3)索引器不是一个变量

    索引器和属性的不同点

    (1)属性以名称来标识,索引器以函数形式标识

    (2)索引器可以被重载,属性不可以

    (3)索引器不能声明为static,属性可以

    C#中的类成员可以是任意类型,包括数组和集合。当一个类包含了数组和集合成员时,索引器将大大简化对数组或集合成员的存取操作。

    [修饰符] 数据类型 this[索引类型 index]  
     
    {  
        get{//获得属性的代码}                                                   
        set{ //设置属性的代码}  
    } 

    http://developer.51cto.com/art/201306/397265.htm

    极客视频:

     http://www.jikexueyuan.com/course/514.html

    using System;
    using System.Collections;
    
    public class IndexerClass
    {
        private string[] name = new string[2];
    
        //索引器必须以this关键字定义,其实这个this就是类实例化之后的对象
        public string this[int index]
        {
            //实现索引器的get方法
            get
            {
                if (index < 2)
                {
                    return name[index];
                }
                return null;
            }
    
            //实现索引器的set方法
            set
            {
                if (index < 2)
                {
                    name[index] = value;
                }
            }
        }
    }
    public class Test
    {
        static void Main()
        {
            //索引器的使用
            IndexerClass Indexer = new IndexerClass();
            //“=”号右边对索引器赋值,其实就是调用其set方法
            Indexer[0] = "张三";
           Indexer[1] = "李四";
            //输出索引器的值,其实就是调用其get方法
            Console.WriteLine(Indexer[0]);
           Console.WriteLine(Indexer[1]);
        }
    }

    什么时候使用索引器?  什么时候只用数组就好了呢?

    以字符串作为下标,对索引器进行存取| 索引器的重载 |多参索引器: http://www.cnblogs.com/ArmyShen/archive/2012/08/27/2659405.html

  • 相关阅读:
    不记住密码
    在Docker中进行Redis主从配置
    Spring Boot系列(8)——RabbitMQ确认、退回模式及死信队列
    RabbitMQ基础
    CentOS只有lo和ens33网卡的解决方案
    Spring Boot系列(7)——自定义异常反馈
    Spring Boot系列(6)——Configurer和Customizer
    以form表单重用方式进行数据列表行删除
    Spring Boot系列(5)——Restful CURD注意事项
    Spring Boot系列(4)——实现国际化
  • 原文地址:https://www.cnblogs.com/viewcozy/p/4606063.html
Copyright © 2020-2023  润新知