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;
        }
    }
}
相关推荐
Qlittleboy9 小时前
PHP的接口参数传递的过多,max_input_vars = 5000
开发语言·php
Aurorar0rua9 小时前
CS50 x 2024 Notes Algorithms - 02
c语言·开发语言·学习方法
en.en..9 小时前
冒泡排序与选择排序完整对比解析
开发语言·数据结构·算法·c#·排序算法
兰令水9 小时前
hot100【acm版】【2026.7.18打卡-java版本】
java·开发语言·算法
cui_ruicheng10 小时前
Python从入门到实战(十三):模块、包与环境管理
开发语言·python
就叫飞六吧10 小时前
子页面和dialog案例
开发语言·javascript·ecmascript
倒流时光三十年10 小时前
Logback 系列(3):三大核心组件 Logger / Appender / Encoder
java·开发语言·logback
淡海水11 小时前
06-04-YooAsset源码-Unity加密解密服务
前端·unity·性能优化·c#·游戏引擎·yooasset
Darkwanderor11 小时前
动、静态库相关内容的详细介绍
linux·c语言·开发语言·c++