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;
        }
    }
}
相关推荐
snow@li38 分钟前
SpringBoot:AOP日志切面全景梳理/原理+流程+实战+避坑
java·开发语言·spring boot
Nil20839 分钟前
C++ emplace_back 与 push_back 详解
开发语言·c++
clear sky .1 小时前
[freertos源码阅读]task.c任务篇
c语言·开发语言
XR1234567881 小时前
工业园区整体组网,方案对比怎么选?
开发语言·php
东东最爱敲键盘1 小时前
day9.C++多态之虚函数
开发语言·c++
码云数智-园园2 小时前
类似小鹅通的知识付费小程序平台有哪些
开发语言
淡海水2 小时前
15-07-YooAsset面试篇-Unity性能优化与内存管理
java·unity·面试·性能优化·c#·游戏引擎
snow@li2 小时前
Java:跨平台原理与JDK、JRE、JVM全景深度解析
java·开发语言·jvm
Livia要学习2 小时前
Python闭包
开发语言·jvm·python
覆东流2 小时前
2.Java程序基础
java·开发语言·后端