C# 索引器的应用
C# 索引器分为:普通索引器(下标为数字),字符串索引器,接口索引器,泛型索引器
1. 普通索引器
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Collections; namespace ConsoleApplication1 { class TempRecord { private float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; public int Length { get { return temps.Length; } } public float this[int index] { get { return temps[index]; } set { temps[index] = value; } } } class Program { static void Main() { TempRecord tempRecord = new TempRecord(); tempRecord[3] = 58.3F; tempRecord[5] = 60.1F; for (int i = 0; i < 10; i++) { if (i < tempRecord.Length) Console.WriteLine("Element #{0} = {1}", i, tempRecord[i]); else Console.WriteLine("Index value of {0} is out of range", i); } Console.ReadLine(); } } }
2. 字符串索引器
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Collections; namespace ConsoleApplication1 { class DayCollection { string[] days = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" }; private int GetDay(string testDay) { int i = 0; foreach (string day in days) { if (day == testDay) return i; i++; } return -1; } public int this[string day] { get { return (GetDay(day)); } } } class Program { static void Main() { DayCollection week = new DayCollection(); Console.WriteLine(week["星期五"]); Console.WriteLine(week["星期八"]); Console.ReadLine(); } } }
3. 接口索引器
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Collections; namespace ConsoleApplication1 { public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : ISomeInterface { private int[] arr = new int[100]; public int this[int index] { get { if (index < 0 || index >= 100) { return 0; } else { return arr[index]; } } set { if (!(index < 0 || index >= 100)) { arr[index] = value; } } } } class Program { static void Main() { IndexerClass test = new IndexerClass(); test[2] = 4; test[5] = 32; for (int i = 0; i <= 10; i++) { Console.WriteLine("Element #{0} = {1}", i, test[i]); } Console.ReadLine(); } } }
4. 泛型索引器
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Collections; namespace ConsoleApplication1 { class SampleCollection<T> { private T[] arr = new T[100]; //this 关键字用于定义索引器。 //索引器不必根据整数值进行索引,自定义决定如何定义特定的查找机制。 //索引器可以有多个形参,例如当访问二维数组时。 //索引器可被重载。 public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } class Program { static void Main() { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = "Hello, World"; Console.WriteLine(stringCollection[0]); Console.ReadLine(); } } }