编辑
2025-09-17
C#
00

目录

引言
索引器的特点
应用场景
自定义集合
多维数据结构
数据验证和转换
缓存实现
数据库行表示
配置管理
惰性加载
索引器的高级特性
使用接口定义索引器
泛型索引器
表达式体索引器
结论

引言

C#索引器是一种强大的语言特性,允许对象像数组一样被索引。它们提供了一种优雅的方式来访问对象的内部数据,使得代码更加直观和易于使用。本文将深入探讨索引器的应用场景、独特特点,并通过丰富的例子来展示其实际用途。

索引器的特点

  1. 类数组访问: 允许使用方括号 [] 访问对象元素。
  2. 灵活的参数: 可以使用任何类型作为索引,不仅限于整数。
  3. 重载能力: 可以在同一个类中定义多个索引器。
  4. 读写控制: 可以分别控制索引器的读取(get)和写入(set)行为。
  5. 计算属性: 索引器可以执行计算,而不仅仅是返回存储的值。

应用场景

自定义集合

最常见的索引器应用是在自定义集合类中。

C#
namespace AppIndex { public class CustomList<T> { private List<T> _items = new List<T>(); public T this[int index] { get => _items[index]; set => _items[index] = value; } public void Add(T item) => _items.Add(item); public int Count => _items.Count; } internal class Program { static void Main(string[] args) { // 使用示例 var fruits = new CustomList<string>(); fruits.Add("Apple"); fruits.Add("Banana"); fruits[1] = "Orange"; Console.WriteLine(fruits[0]); Console.WriteLine(fruits[1]); Console.ReadLine(); } } }

image.png

多维数据结构

索引器非常适合表示多维数据,如矩阵或图像像素。

C#
namespace AppIndex { public class Matrix { private int[,] _data; public Matrix(int rows, int cols) { _data = new int[rows, cols]; } public int this[int row, int col] { get => _data[row, col]; set => _data[row, col] = value; } } internal class Program { static void Main(string[] args) { // 使用示例 var matrix = new Matrix(3, 3); matrix[0, 0] = 1; matrix[1, 1] = 5; Console.WriteLine(matrix[0, 0]); Console.WriteLine(matrix[1, 1]); Console.ReadLine(); } } }

image.png

数据验证和转换

索引器可以在访问或设置值时执行验证或转换。

C#
public class ValidatedArray { private int[] _array = new int[10]; public int this[int index] { get => _array[index]; set { if (value < 0) throw new ArgumentException("Value must be non-negative"); _array[index] = value; } } } // 使用示例 var arr = new ValidatedArray(); arr[0] = 5; // 正常工作 // arr[1] = -1; // 抛出异常

缓存实现

索引器可以用于实现简单的缓存机制。

C#
namespace AppIndex { public class SimpleCache { private Dictionary<string, object> _cache = new Dictionary<string, object>(); public object this[string key] { get => _cache.TryGetValue(key, out var value) ? value : null; set => _cache[key] = value; } } internal class Program { static void Main(string[] args) { // 使用示例 var cache = new SimpleCache(); cache["user"] = new { Name = "Rick", Age = 25 }; var user = cache["user"]; Console.WriteLine(((dynamic)user).Name); Console.ReadLine(); } } }

image.png

数据库行表示

索引器可以用来表示数据库的行,使用列名作为索引。

C#
namespace AppIndex { public class DatabaseRow { private Dictionary<string, object> _data = new Dictionary<string, object>(); public object this[string columnName] { get => _data.TryGetValue(columnName, out var value) ? value : null; set => _data[columnName] = value; } } internal class Program { static void Main(string[] args) { // 使用示例 var row = new DatabaseRow(); row["Name"] = "John Doe"; row["Age"] = 30; Console.WriteLine($"Name: {row["Name"]}, Age: {row["Age"]}"); Console.ReadLine(); } } }

image.png

配置管理

索引器可以用于管理应用程序的配置设置。

C#
namespace AppIndex { public class AppConfig { private Dictionary<string, string> _settings = new Dictionary<string, string>(); public string this[string key] { get => _settings.TryGetValue(key, out var value) ? value : null; set => _settings[key] = value; } public void LoadFromFile(string path) { // 从文件加载配置 } public void SaveToFile(string path) { // 保存配置到文件 } } internal class Program { static void Main(string[] args) { // 使用示例 var config = new AppConfig(); config["LogLevel"] = "Info"; config["MaxConnections"] = "100"; Console.WriteLine($"Log Level: {config["LogLevel"]}"); Console.ReadLine(); } } }

image.png

惰性加载

索引器可以用于实现惰性加载,只在需要时才加载数据。

C#
namespace AppIndex { public class LazyLoadList<T> { private List<Lazy<T>> _items = new List<Lazy<T>>(); public void Add(Func<T> valueFactory) { _items.Add(new Lazy<T>(valueFactory)); } public T this[int index] { get => _items[index].Value; } } internal class Program { static void Main(string[] args) { // 使用示例 var lazyList = new LazyLoadList<string>(); lazyList.Add(() => { Console.WriteLine("Loading item 0..."); return "Item 0"; }); lazyList.Add(() => { Console.WriteLine("Loading item 1..."); return "Item 1"; }); Console.WriteLine(lazyList[0]); Console.WriteLine(lazyList[0]); Console.ReadLine(); } } }

image.png

索引器的高级特性

使用接口定义索引器

接口可以包含索引器定义,允许多个类实现相同的索引访问模式。

C#
public interface IIndexable<T> { T this[int index] { get; set; } } public class IndexableList<T> : IIndexable<T> { private List<T> _items = new List<T>(); public T this[int index] { get => _items[index]; set => _items[index] = value; } }

泛型索引器

索引器可以是泛型的,提供更大的灵活性。

C#
namespace AppIndex { public class GenericIndexer<TKey, TValue> { private Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>(); public TValue this[TKey key] { get => _dictionary.TryGetValue(key, out var value) ? value : default; set => _dictionary[key] = value; } } internal class Program { static void Main(string[] args) { // 使用示例 var indexer = new GenericIndexer<string, int>(); indexer["One"] = 1; indexer["Two"] = 2; Console.WriteLine(indexer["One"]); Console.ReadLine(); } } }

表达式体索引器

C# 6.0引入了表达式体成员,可以用于简化索引器的定义。

C#
public class CompactIndexer { private int[] _data = new int[10]; public int this[int i] { get => _data[i]; set => _data[i] = value; } }

结论

C#索引器是一个强大而灵活的特性,它不仅可以简化代码,还能提高代码的可读性和可维护性。通过本文的深入探讨和丰富示例,我们看到了索引器在各种场景下的应用,从简单的集合访问到复杂的数据管理和安全控制。

索引器的灵活性使得它们可以适应各种编程需求,而其直观的语法使得代码更易于理解和使用。通过合理使用索引器,开发者可以创建出更加优雅和高效的C#程序。

随着你在实际项目中越来越多地使用索引器,你会发现它们是提高代码质量和开发效率的有力工具。希望本文能够启发你在日常编程中更好地利用这一强大特性。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!