C# .NET 索引器的基本使用 发表于 2020-08-18 | 更新于 2020-11-14 | 分类于 编程爱好 | 评论数: | 阅读次数: 索引器和属性差不多,属性是一对一,而索引器是一对多而已。 (一) int 索引12345678910111213141516171819202122232425262728293031323334class Program{ static void Main(string[] args) { MyClass mc = new MyClass(); mc[0] = "胡文杰"; mc[1] = "杨佳"; Console.WriteLine(mc[0]); Console.WriteLine(mc[1]); Console.Read(); }}class MyClass{ private string[] name = new string[2]; // 关键:用 this 代替,类型也可以用 string public string this[int index] { get { if (index >= 0 && index < name.Length) { return name[index]; } else { return name[0]; } } set { if (index >=0 && index < name.Length) { name[index] = value; } } }} 输出: 12胡文杰杨佳 string 索引12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667using System;namespace RefTest{ class Employee { public string name; public string Age; public string Gender; public Employee(string n, string a, string g) { name = n; Age = a; Gender = g; } public string this[string str] { set { switch (str) { case "姓名": name = value; break; case "年龄": Age = value; break; case "性别": Gender = value; break; //default: //throw new Exception().Message; } } get { switch (str) { case "姓名": return name; case "年龄": return Age; case "性别": return Gender; default: throw new ArgumentOutOfRangeException("index"); } } } class Program { static void Main() { Employee employee = new Employee("周杰伦", "12", "男"); Console.WriteLine(employee["姓名"] + " " + employee["年龄"] + " " + employee["性别"]); Console.WriteLine("\n改名:"); employee["姓名"] = "猪八戒"; Console.WriteLine(employee["姓名"] + " " + employee["年龄"] + " " + employee["性别"]); Console.ReadKey(); } } }} 输出: 1234周杰伦 12 男改名:猪八戒 12 男 感谢支持! 打赏 微信支付 支付宝 本文作者: huvjie 本文链接: https://blog.huvjie.com/2020/08/18/200818N01/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!