c# 索引器

索引器(Indexer)允许你像访问数组一样,通过索引访问对象的属性或数据。索引器的主要用途是在对象内部封装复杂的数据结构,使得数据访问更加直观。下面是关于 C# 索引器的详细解释及示例:

基本语法

索引器的语法类似于属性,但它使用方括号 [] 来定义索引参数。索引器通常定义在类或结构体内部。

public class MyClass
{
    private int[] data = new int[10];

    // 索引器的定义
    public int this[int index]
    {
        get
        {
            // 索引器的 getter 方法
            if (index < 0 || index >= data.Length)
                throw new IndexOutOfRangeException();
            return data[index];
        }
        set
        {
            // 索引器的 setter 方法
            if (index < 0 || index >= data.Length)
                throw new IndexOutOfRangeException();
            data[index] = value;
        }
    }
}

示例解释

  1. 定义索引器:
  • public int this[int index] 定义了一个接受整数索引的索引器。this 关键字表明这是一个索引器而不是普通的属性。
  1. Getter 和 Setter:
  • get 方法用于获取索引器的值。它检查索引是否在有效范围内,然后返回相应的值。
  • set 方法用于设置索引器的值。它检查索引是否在有效范围内,然后设置相应的值。
  1. 使用索引器:
  • 索引器可以像数组一样使用。例如:
MyClass obj = new MyClass();
obj[0] = 10;   // 调用索引器的 setter 方法
int value = obj[0]; // 调用索引器的 getter 方法
Console.WriteLine(value); // 输出 10

具有多个参数的索引器

索引器不仅可以有一个参数,还可以有多个参数。示例如下:

public class MultiDimensionalClass
{
    private int[,] data = new int[5, 5];

    // 多维索引器的定义
    public int this[int row, int col]
    {
        get
        {
            if (row < 0 || row >= data.GetLength(0) || col < 0 || col >= data.GetLength(1))
                throw new IndexOutOfRangeException();
            return data[row, col];
        }
        set
        {
            if (row < 0 || row >= data.GetLength(0) || col < 0 || col >= data.GetLength(1))
                throw new IndexOutOfRangeException();
            data[row, col] = value;
        }
    }
}

使用具有多个参数的索引器

MultiDimensionalClass obj = new MultiDimensionalClass();
obj[2, 3] = 42;   // 调用多维索引器的 setter 方法
int value = obj[2, 3]; // 调用多维索引器的 getter 方法
Console.WriteLine(value); // 输出 42

相关推荐

  1. 索引C#】

    2024-07-22 16:32:07       53 阅读
  2. c# 索引

    2024-07-22 16:32:07       17 阅读
  3. C# 接口_索引_命名空间

    2024-07-22 16:32:07       33 阅读
  4. C# 索引的范例和要点

    2024-07-22 16:32:07       40 阅读
  5. C#学习3--实验:索引和接口

    2024-07-22 16:32:07       30 阅读
  6. 学懂C#编程:C# 索引(Indexer)的概念及用法

    2024-07-22 16:32:07       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 16:32:07       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 16:32:07       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 16:32:07       45 阅读
  4. Python语言-面向对象

    2024-07-22 16:32:07       55 阅读

热门阅读

  1. 初入C语言的主要难点

    2024-07-22 16:32:07       17 阅读
  2. PostgreSQL 慢 SQL 排查

    2024-07-22 16:32:07       18 阅读
  3. YARA:第十六章-libyara之C API手册(威胁检测)

    2024-07-22 16:32:07       15 阅读
  4. ipython 的使用技巧的整理

    2024-07-22 16:32:07       17 阅读
  5. sklearn基础教程

    2024-07-22 16:32:07       17 阅读
  6. 自然语言处理基础【1】词嵌入

    2024-07-22 16:32:07       14 阅读
  7. 【C++ 初始化列表】

    2024-07-22 16:32:07       14 阅读