当前位置:首页 > 文章列表 > 文章 > 软件教程 > C#.NET 索引器完全解析:语法、场景与最佳实践

C#.NET 索引器完全解析:语法、场景与最佳实践

2026-08-21 10:10:32 0浏览 收藏

简介

在C#中,索引器(Indexer)是一种特殊的属性,它让类或结构体能够像数组那样,通过索引语法(比如 obj[0])来访问或修改对象内部的成员。简而言之,它把对象实例当作“可索引的集合”,提供了类似数组的访问方式。

C#.NET 索引器完全解析:语法、场景与最佳实践

  • 核心特性:

    • 类似于属性(Property),但带有参数(通常是索引值,如整数或字符串)。

    • 支持 get 和 set 访问器,与属性类似。

    • 可以重载(overload),允许不同类型的索引参数。

    • 语法:public 类型 this[参数类型 参数名] { get { ... } set { ... } }

  • 适用范围:类、结构体、接口。不能在委托或枚举中使用。

索引器本质上是方法(get/set),但编译器将其转换为特殊的属性调用,隐藏了底层实现细节。

语法结构:

public  this[ index]
{
    get { ... }
    set { ... }
}
  • this[...] 表示作用于当前对象实例。

  • 可以有多个索引参数(如二维索引)。

为什么使用索引器?

在面向对象编程的领域里,直接将内部数组或集合暴露出来(就像 public int[] Data { get; } 这样),会让封装性大打折扣,客户端可以随随便便地去修改它。而索引器则能提供一种受控的访问方式:

  • 封装性:隐藏内部存储(如 List、Dictionary),允许验证、转换或缓存逻辑。

  • 直观性:代码更像数组操作,提升可读性(e.g., cache["key"] = value; 而非 cache.Set("key", value);)。

  • 适用场景:

    • 模拟数组/集合(如自定义列表、矩阵)。

    • 字典式访问(字符串键)。

    • 多维数据(如图像像素访问)。

    • 与 LINQ 或 foreach 集成(需实现 IEnumerable)。

相比普通方法,索引器更简洁;相比属性,它支持参数化访问。

基本示例

public class MyList
{
    private string[] _data = new string[5];

    public string this[int index]
    {
        get => _data[index];
        set => _data[index] = value;
    }
}

使用方式:

var list = new MyList();
list[0] = "Hello";
list[1] = "World";

Console.WriteLine(list[0]); // 输出:Hello
Console.WriteLine(list[1]); // 输出:World

看起来就像数组访问,但其实内部是属性访问。

索引器与属性的关系

对比项属性 (Property)索引器 (Indexer)
名称有名字名为 this
参数无参数有一个或多个参数
调用方式obj.Propertyobj[index]
典型用途访问字段值访问集合或映射内容

索引器的底层机制

编译后:

obj[index]

其实会被编译为:

obj.get_Item(index);    // 读取
obj.set_Item(index, x); // 赋值

也就是说,索引器就是名为 Item 的一对 get/set 方法(CLR 级别)。

不同类型的索引器

整数索引器

public class IntArrayWrapper
{
    private int[] _array;

    public IntArrayWrapper(int size)
    {
        _array = new int[size];
    }

    public int this[int index]
    {
        get => _array[index];
        set => _array[index] = value;
    }

    public int Length => _array.Length;
}

// 使用
var wrapper = new IntArrayWrapper(5);
wrapper[0] = 10;
wrapper[1] = 20;
Console.WriteLine(wrapper[0]); // 输出: 10

字符串索引器

public class DictionaryWrapper
{
    private Dictionarystring, string> _dictionary = new Dictionarystring, string>();

    public string this[string key]
    {
        get
        {
            _dictionary.TryGetValue(key, out string value);
            return value;
        }
        set
        {
            _dictionary[key] = value;
        }
    }
}

// 使用
var dictWrapper = new DictionaryWrapper();
dictWrapper["name"] = "John";
dictWrapper["age"] = "30";

Console.WriteLine(dictWrapper["name"]); // 输出: John

多参数索引器

public class Matrix
{
    private double[,] _matrix;

    public Matrix(int rows, int columns)
    {
        _matrix = new double[rows, columns];
    }

    // 多参数索引器
    public double this[int row, int column]
    {
        get => _matrix[row, column];
        set => _matrix[row, column] = value;
    }

    public int Rows => _matrix.GetLength(0);
    public int Columns => _matrix.GetLength(1);
}

// 使用
var matrix = new Matrix(3, 3);
matrix[0, 0] = 1.0;
matrix[1, 1] = 2.0;
matrix[2, 2] = 3.0;

Console.WriteLine(matrix[1, 1]); // 输出: 2.0

重载索引器

public class MultiIndexCollection
{
    private Liststring> _items = new Liststring>();

    public void Add(string item) => _items.Add(item);

    // 整数索引器
    public string this[int index]
    {
        get => _items[index];
        set => _items[index] = value;
    }

    // 字符串索引器 - 通过名称查找
    public string this[string name]
    {
        get => _items.Find(item => item.StartsWith(name));
    }
}

// 使用
var collection = new MultiIndexCollection();
collection.Add("Apple");
collection.Add("Banana");
collection.Add("Cherry");

Console.WriteLine(collection[0]);    // 输出: Apple
Console.WriteLine(collection["B"]);  // 输出: Banana

高级用法

只读索引器

public class Settings
{
    private readonly Dictionarystring, string> _values = new();

    public string this[string key]
    {
        get => _values.TryGetValue(key, out var value) ? value : string.Empty;
        set => _values[key] = value;
    }
}

使用:

var s = new Settings();
s["Language"] = "Chinese";
s["Theme"] = "Dark";

Console.WriteLine(s["Language"]); // Chinese

只写:

public string this[int index]
{
    set => _data[index] = value;
}

索引器可以被继承或重写

父类定义:

public class Base
{
    public virtual string this[int index]
    {
        get => $"Base:{index}";
        set => Console.WriteLine($"Set Base[{index}]={value}");
    }
}

子类重写:

public class Derived : Base
{
    public override string this[int index]
    {
        get => $"Derived:{index}";
        set => Console.WriteLine($"Set Derived[{index}]={value}");
    }
}

接口中的索引器

public interface IListContainerT>
{
    T this[int index] { get; set; }
    int Count { get; }
}

public class MyListT> : IListContainerT>
{
    private List _items = new List();

    public T this[int index]
    {
        get => _items[index];
        set => _items[index] = value;
    }

    public int Count => _items.Count;

    public void Add(T item) => _items.Add(item);
}

实际应用示例

配置管理器

public class Configuration
{
    private readonly Dictionarystring, object> _settings = new Dictionarystring, object>();

    public object this[string key]
    {
        get => _settings.TryGetValue(key, out object value) ? value : null;
        set => _settings[key] = value;
    }

    public T GetT>(string key, T defaultValue = default)
    {
        if (_settings.TryGetValue(key, out object value) && value is T typedValue)
        {
            return typedValue;
        }
        return defaultValue;
    }
}

// 使用
var config = new Configuration();
config["DatabaseConnection"] = "Server=localhost;Database=Test;";
config["Timeout"] = 30;

string connection = config.Getstring>("DatabaseConnection");
int timeout = config.Getint>("Timeout");

自定义集合类

public class SmartCollectionT>
{
    private T[] _items;
    
    public SmartCollection(int size) => _items = new T[size];
    
    public T this[int index]
    {
        get => _items[index];
        set => _items[index] = value;
    }
    
    // 重载索引器
    public T this[string name] => FindByName(name);
    
    private T FindByName(string name)
    {
        // 根据名称查找逻辑...
    }
}

数据访问层封装

public class DataRepository
{
    private List _customers = new();
    
    public Customer this[int id]
    {
        get => _customers.FirstOrDefault(c => c.Id == id);
    }
    
    public Customer this[string email]
    {
        get => _customers.FirstOrDefault(c => c.Email == email);
    }
}

索引器与其他特性结合

索引器与泛型

public class GenericCollectionT>
{
    private T[] _items = new T[10];
    
    public T this[int index]
    {
        get => _items[index];
        set => _items[index] = value;
    }
}

索引器与模式匹配(C# 8.0+)

if (collection is IIndexableint, string> indexable)
{
    Console.WriteLine(indexable[0]);
}

索引器与范围支持(C# 8.0+)

public class RangeCollection
{
    private int[] _items = {1, 2, 3, 4, 5};
    
    public int[] this[Range range]
    {
        get => _items[range];
    }
}

// 使用
var collection = new RangeCollection();
int[] sub = collection[1..4]; // [2, 3, 4]

常见应用场景

场景示例
模拟集合/字典访问myDict[key]
操作二维数据matrix[row, col]
管理配置项settings["Theme"]
实现对象简洁访问接口student["Name"]、api["token"]
C# 正则表达式(4):分支与回溯引用C# 正则表达式(4):分支与回溯引用
上一篇
C# 正则表达式(4):分支与回溯引用
一篇搞定 dotnet ef:EF Core 常用命令与实战指南
下一篇
一篇搞定 dotnet ef:EF Core 常用命令与实战指南
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • PubMedQA数据集详解:生物医学问答基准、功能与应用指南
    PubMedQA
    深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
    343次使用
  • H2O EvalGPT:开源LLM大模型评估与排行榜工具
    H2O EvalGPT
    H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
    404次使用
  • LMArena是什么?伯克利AI模型评估平台使用指南与功能解析
    LMArena
    LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
    404次使用
  • 斯坦福HELM:大语言模型Holistic Evaluation整体评估框架详解
    HELM
    深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
    363次使用
  • MMBench详解:多模态大模型基准测试、功能特点与使用指南
    MMBench
    MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
    186次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议 和 隐私政策
返回登录
  • 重置密码