C# 索引器(Indexer)
系统讲解 C# 索引器(this[...])的虚拟数组封装机制、与属性的异同、边界检查以及按不同参数类型和参数个数重载索引器的方法,并附本地 csc.exe 实测。
学完这一章,你能够
- 系统讲解 C# 索引器(this[...])的虚拟数组封装机制、与属性的异同、边界检查以及按不同参数类型和参数个数重载索引器的方法,并附本地 csc.exe 实测。
索引器概念与基本语法
索引器(Indexer)允许类或结构体的实例像数组一样通过下标运算符 `[ ]` 访问内部元素,使自定义容器具备类似“虚拟数组”的直观调用体验。声明一维索引器时使用 `element-type this[int index]` 形式,并在主体内定义 `get` 与 `set` 访问器(`set` 内同样通过隐式参数 `value` 获取待写入的值)。
索引器与属性的区别及一维实测
索引器在语法和封装思想上与属性高度相似,都依赖 `get`/`set` 访问器控制读写,但定位不同:属性拥有显式成员名,通常对应对象的某一项独立特征;索引器没有自定义名称,必须以 `this` 关键字声明并接收至少一个索引参数,用于定位对象内部集合中的特定槽位。在 `IndexedNames` 示例中,内部维护长度为 `10` 且初始填充 `"N. A."` 的字符串数组,索引器在读写前均校验 `0 <= index < Size`:越界读取返回空串 `""`,越界写入被安全忽略。本站实测写入前 7 项后顺序读取 10 项精确得到 7 个姓名与 3 个 `"N. A."`,并确认 `-1` 与 `99` 越界访问不抛异常且不污染既有槽位。
索引器重载与多参数索引
与方法类似,同一类型内可以重载多个索引器,只要参数列表的类型或个数不同即可——索引参数完全不必局限于整型,例如为 `IndexedNames` 追加只读字符串索引器 `public int this[string name]` 即可通过姓名反查下标位置(如 `names["Nuha"]` 返回 `2`)。工程细节提醒:若按循环查不到匹配项时直接返回循环终值 `size`(`10`)容易与长度混淆,工程实现更推荐返回 `-1` 明确标识“未找到”。此外,索引器还支持多维参数(如 `this[int row, int col]`),本站已在 `Grid2D` 二维矩阵实测中一并验证。
运行 csc.exe (.NET Framework 4.x) 一维索引器、越界保护、字符串重载与二维多参索引器实测
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharpIndexerLab
{
internal class IndexedNames
{
public static readonly int Size = 10;
private readonly string[] namelist = new string[Size];
public IndexedNames()
{
for (int i = 0; i < Size; i++)
{
namelist[i] = "N. A.";
}
}
public string this[int index]
{
get
{
if (index >= 0 && index <= Size - 1)
{
return namelist[index];
}
return "";
}
set
{
if (index >= 0 && index <= Size - 1)
{
namelist[index] = value;
}
}
}
public int this[string name]
{
get
{
for (int i = 0; i < Size; i++)
{
if (namelist[i] == name)
{
return i;
}
}
return -1;
}
}
}
internal class Grid2D
{
private readonly int[,] cells;
public Grid2D(int rows, int cols)
{
cells = new int[rows, cols];
}
public int this[int row, int col]
{
get { return cells[row, col]; }
set { cells[row, col] = value; }
}
}
internal class Program
{
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
// Case 1: Int indexer virtual array traversal
List<string> items = new List<string>();
for (int i = 0; i < IndexedNames.Size; i++)
{
items.Add(names[i]);
}
cases.Add(CaseJson(
"int_indexer_virtual_array",
"Verify 1D int indexer get/set and default initialization for unassigned slots",
"Zara,Riz,Nuha,Asif,Davinder,Sunil,Rubic,N. A.,N. A.,N. A.",
string.Join(",", items.ToArray())
));
// Case 2: Out-of-range bounds safety
names[-1] = "InvalidLow";
names[99] = "InvalidHigh";
string actual2 = string.Format("low='{0}';high='{1}';slot0='{2}'", names[-1], names[99], names[0]);
cases.Add(CaseJson(
"indexer_bounds_safety",
"Verify out-of-range get returns empty string and out-of-range set is safely ignored",
"low='';high='';slot0='Zara'",
actual2
));
// Case 3: Overloaded string indexer
int nuhaIdx = names["Nuha"];
int missingIdx = names["Unknown"];
string actual3 = string.Format("Nuha={0};Unknown={1}", nuhaIdx, missingIdx);
cases.Add(CaseJson(
"overloaded_string_indexer",
"Verify overloaded string indexer resolves 'Nuha' to index 2 and missing entry to -1",
"Nuha=2;Unknown=-1",
actual3
));
// Case 4: Multi-parameter 2D indexer
Grid2D grid = new Grid2D(2, 3);
grid[0, 1] = 15;
grid[1, 2] = 42;
string actual4 = string.Format("0,1={0};1,2={1};0,0={2}", grid[0, 1], grid[1, 2], grid[0, 0]);
cases.Add(CaseJson(
"multi_param_matrix_indexer",
"Verify multi-parameter indexer this[int row, int col] on Grid2D",
"0,1=15;1,2=42;0,0=0",
actual4
));
Console.WriteLine(string.Format(
"{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
Environment.Version.ToString(),
string.Join(",", cases.ToArray())
));
}
}
}
- 核对 IndexedNames 10 项读取、-1/99 越界保护、字符串索引器定位 Nuha=2 与缺失返回 -1 及 Grid2D 二维索引器全部通过。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
当前源码 SHA256:981cef0f60a8559d932bc056ee269d1092502a059c3ed256a75eccb2de166dd1
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
ZIP SHA256:7a8edd5f4d5c64c303d76478d9770a3d8d495a8cc7a3b393327c77e9af60a539
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
C# 中同一个类能否同时定义 `this[int index]` 与 `this[string key]` 两个索引器?索引器能否声明为 `static`?
展开参考解答
可以,只要参数类型、数量或顺序不同即可重载多个索引器(且返回类型可以不同)。索引器不能声明为 `static`,因为它必须通过 `this` 绑定到具体对象实例。