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;
        }
    }
}
相关推荐
Sarvartha3 小时前
final 关键字
java·开发语言
程序员Sunday3 小时前
JavaScript 事件循环面试题,宏任务与微任务怎么执行|Sunday面试指南
开发语言·javascript·面试·校招·事件循环·程序员sunday
zhangzeyuaaa4 小时前
Ruby 多线程、GVL(GIL)与 Mutex 完全指南
开发语言·前端·ruby
谢亮_vipxieliang5 小时前
用 PHP 构建轻量级 REST API:从路由到鉴权的完整实践
开发语言·后端·php
思无邪665 小时前
用 AI 做 JS 逆向:从抓包到复现的完整方法论
开发语言·javascript·人工智能
H.莓飛6 小时前
【数据结构】二叉树_OJ题
linux·开发语言·数据结构·算法
零基础1237 小时前
Ubuntu 常用命令汇总
linux·运维·开发语言
外收内放7 小时前
Python基础语法练习题(57-58)
开发语言·python
时间的拾荒人7 小时前
Qt 界面美化实战:QSS 样式表
开发语言·qt·面试
杨运交8 小时前
[076][核心模块]构建优雅的Java异常处理框架:从错误码到全局异常处理
java·开发语言