一。声明与使用
像数组一样访问数据,像属性一样的经构
using System; namespace Indexer { class Employee { private string LastName; private string FirstName; private string CityOfBirth; public string this[int index] { set { switch(index) { case 0: LastName = value; break; case 1: FirstName = value; break; case 2: CityOfBirth = value; break; default: throw new ArgumentOutOfRangeException("index"); } } get { switch(index) { case 0: return LastName; case 1: return FirstName; case 2: return CityOfBirth; default: throw new ArgumentOutOfRangeException("index"); } } } } class Program { static void Main(string[] args) { Employee employee = new Employee(); employee[0] = "Qian"; employee[1] = "Keefe"; employee[2] = "LuJiang"; Console.WriteLine($"{employee[0]} {employee[1]} {employee[2]}"); } } }
二。索引器重载
using System; namespace IndexerOverload { class MyClass { string Temp0; string Temp1; string Temp2; string Temp3; int MyInt0 = 0; int MyInt1 = 1; public string this[int index] { get { return (0 == index) ? Temp0 : Temp1; } set { if (0 == index) Temp0 = value; else Temp1 = value; } } public string this[int index1, int index2] { get { if (index1 == 0 && index2 == 0) return Temp0; if (index1 == 0 && index2 == 1) return Temp1; if (index1 == 1 && index2 == 0) return Temp2; if (index1 == 1 && index2 == 1) return Temp3; throw new ArgumentOutOfRangeException("index"); } set { if (index1 == 0 && index2 == 0) Temp0 = value; if (index1 == 0 && index2 == 1) Temp1 = value; if (index1 == 1 && index2 == 0) Temp2 = value; if (index1 == 1 && index2 == 1) Temp3 = value; //throw new ArgumentOutOfRangeException("index"); } } public int this[float index] { get { if (index < 1.0) { return MyInt0; } else { return MyInt1; } } } } class Program { static void Main(string[] args) { MyClass mc = new MyClass(); mc[0] = "Illustrated"; mc[1] = "C# 7"; Console.WriteLine($"{mc[0]} {mc[1]}"); mc[1, 0] = "Fifth Edition"; mc[1, 1] = "Daniel Solis & Cal Schrotenboer"; Console.WriteLine($"{mc[0]} {mc[1]} {mc[1, 0]} {mc[1, 1]}"); Console.WriteLine($"{mc[0.4f]} {mc[1.3f]}"); } } }
标签:index,return,string,mc,索引,index2,index1 From: https://www.cnblogs.com/duju/p/16771990.html