C#索引器demo
//简单实例
public class MyClass { private string[] myArray = new string[5]; // 索引器 public string this[int index] { get { return myArray[index]; } set { myArray[index] = value; } } } public class Program { static void Main(string[] args) { MyClass myObject = new MyClass(); // 设置索引器的值 myObject[0] = "Hello"; myObject[1] = "World"; // 获取索引器的值 Console.WriteLine(myObject[0]); // 输出: Hello Console.WriteLine(myObject[1]); // 输出: World } } //多维数组实例 public class MyMatrix { private int[,] matrix = new int[3, 3]; // 索引器 public int this[string row, string column] { get { int rowIndex = GetRowIndex(row); int columnIndex = GetColumnIndex(column); return matrix[rowIndex, columnIndex]; } set { int rowIndex = GetRowIndex(row); int columnIndex = GetColumnIndex(column); matrix[rowIndex, columnIndex] = value; } } private int GetRowIndex(string row) { // 在此处根据行名返回相应的行索引 // 这里只是一个示例,您需要根据实际需求进行实现 if (row == "A") return 0; else if (row == "B") return 1; else if (row == "C") return 2; else throw new ArgumentException("Invalid row name"); } private int GetColumnIndex(string column) { // 在此处根据列名返回相应的列索引 // 这里只是一个示例,您需要根据实际需求进行实现 if (column == "X") return 0; else if (column == "Y") return 1; else if (column == "Z") return 2; else throw new ArgumentException("Invalid column name"); } } public class Program { static void Main(string[] args) { MyMatrix myMatrix = new MyMatrix(); // 设置索引器的值 myMatrix["A", "X"] = 1; myMatrix["B", "Y"] = 2; // 获取索引器的值 Console.WriteLine(myMatrix["A", "X"]); // 输出: 1 Console.WriteLine(myMatrix["B", "Y"]); // 输出: 2 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2023-02-21 .Net依赖注入、控制反转