C#中的索引器

索引器是一类共对象在外部以一种更便捷的方式访问或修改类内变量的方法,例如:依据索引访问类内集合性质的元素以及其他更加自由的操作。在语法上,综合了函数与成员属性的写法。允许重载。其内部的get/set规则也与成员属性类似。

cs 复制代码
namespace ConsoleApp5
{
    class Person
    {
        public Person()
        {
            array = new int[10, 10]; // 或根据需要设定维度
        }
        private string name;
        private int age;
        private Person[] friends;

        private int[,] array;
        //利用索引器访问二维数组
        public int this[int i, int j]
        {
            get { return array[i, j]; }
            set { array[i, j] = value; }
        }
        //利用索引器传入的字符串返回对应的成员变量
        private string this[string str]
        {
            get
            {
                switch (str)
                {
                    case "name":
                        return this.name;
                        break;
                    case "age":
                        return this.age.ToString();
                    default:
                        return "";
                }

            }
        }
        //利用索引器访问一维数组(允许添加额外逻辑)
        public Person this[int index]
        {
            get
            {
                if (friends == null || friends.Length - 1 < index)
                {
                    return null;
                }
                else
                {
                    return friends[index];
                }
            }
            set
            {
                if (friends == null)
                {
                    friends = new Person[] { value };
                }
                else if (friends.Length - 1 < index)
                {
                    friends[friends.Length - 1] = value;
                }
                else
                {
                    friends[index] = value;
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p[0] = new Person();
            Console.WriteLine(p[0]);
            p[0, 0] = 10;
        }
    }
}
相关推荐
福大大架构师每日一题6 小时前
agno v2.8.7 发布:顾问模型、精准路线、调度能力全面升级,10项关键修复一次看懂
java·开发语言·数据库
老洋葱Mr_Onion6 小时前
【C++】CSP-J复赛dp问题(含模板题)
开发语言·c++
李永奉14 小时前
C语言-嵌入式开发C语言常用预处理指令合集
c语言·开发语言
上海安当技术15 小时前
敏感数据怎么防拖库?信封加密(DEK+KEK 二层密钥)架构设计与 Java 实战
java·开发语言·python
我是唐青枫15 小时前
Java JCommander 实战详解:用注解解析命令行参数
java·开发语言
大鹏说大话15 小时前
C++ 内存布局详解:类、虚函数、虚表底层原理
java·开发语言
键盘会跳舞15 小时前
C++:容器适配器 queue 的源码级拆解
开发语言·c++·queue
Loge编程生活16 小时前
打卡信奥刷题(3449)用C++实现信奥题 P10429 [蓝桥杯 2024 省 B] 拔河
开发语言·数据结构·c++·算法·青少年编程
在世修行17 小时前
从零打造 C# 工业视觉检测系统(八):Modbus RTU 协议解析与 PLC 剔除控制实战
开发语言·c#
sunburn-17 小时前
Java 队列全面详解:从入门到面试实战
java·开发语言·汇编·ide·idea