在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1. 什么是索引 索引是一组get和set访问器,类似于属性的访问器。 2. 索引和属性
3. 声明索引
4. 两个索引的示例 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication11 { class Employee { public string LastName; public string FirstName; public 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 Example { int Temp0; int Temp1; public int this[int index] { get { return (0 == index) ? Temp0 : Temp1; } set { if (0 == index) { Temp0 = value; } else { Temp1 = value; } } } } class Program { static void Main(string[] args) { Employee emp1 = new Employee(); emp1[0] = "Doe"; emp1[1] = "Jane"; emp1[2] = "Dallas"; Console.WriteLine("{0}", emp1[0]); Console.WriteLine("{0}", emp1[1]); Console.WriteLine("{0}", emp1[2]); Example a = new Example(); a[0] = 15; a[1] = 20; Console.WriteLine("Values--T0:{0}, T1:{1}", a[0], a[1]); Console.ReadLine(); } } } 5. 索引重载 class MyClass { public string this[int index] { get { return "Testing"; } set { } } public string this[int index1, int index2] { get { return "Testing"; } set { } } public int this[float index] { get { return 3; } set { } } }
默认情况下,成员的两个访问器有和成员自身相同的访问级别。在特定情况下,成员的访问器可以有不同的访问级别。
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论