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

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

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

简介

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

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

  • 核心特性:

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

    • 支持 getset 访问器,与属性类似。

    • 可以重载(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);)。

  • 适用场景:

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

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

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

    • LINQforeach 集成(需实现 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推荐
  • ljg-skills -
    ljg-skills
    ljg-skills 是李继刚开源的 AI 技能与提示词集合,面向大模型使用者整理了一批可复用的 prompt、角色设定和任务技能模板,适合用于学习提示词设计、搭建个人 AI 工作流和沉淀团队常用智能体能力。
    5046次使用
  • MELO音乐 - AI 音乐生成平台,支持多模态创作能力
    MELO音乐
    MELO音乐是一站式AI视频与音乐制作助手,对标suno, udio的高品质体验。提供伴奏生成、原创写词、无损导出、哼唱识曲、混音变声等全套音频与短视频编辑工具。无论是流行Kpop、电音说唱、民谣古风、摇滚儿歌还是商用轻音乐,MELO为你免费谱曲,轻松做同款!
    4576次使用
  • UniScribe - AI 免费在线音视频转文字平台
    UniScribe
    UniScribe 是一款 AI 音视频转文字与内容整理工具,支持上传音频、视频文件或粘贴 YouTube 链接,自动生成转写文本、摘要、思维导图和关键问题,并支持多格式导出,适合会议记录、课程学习、访谈整理和内容创作复盘。
    4532次使用
  • 剧云 - 免费 AI 智能中文剧本创作平台
    剧云
    剧云是专业中文剧本创作平台,安全稳定运行十余年,集成AI编剧、剧本医生审核、人物小传、剧情关系图、大纲编写、多人协作、Word导入导出、版权管控功能,数据安全防护,轻松高效创作剧本。
    4785次使用
  • 万象有声 - AI 一站式有声内容创作平台
    万象有声
    万象有声,一个专为有声创作者打造的新一代智能有声内容创作平台。平台提供专业的智能拆章、智能画本编辑、AI配音、AI生成音效、后期制作、智能对轨、智能审听等有声创作全流程工具,可以帮助创作者高效、低成本创作出引人入胜的有声作品。立即体验,让有声书制作更简单!
    4738次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码