聲明索引的語法如此下,請注意以下幾點:
聲明索引類似于聲明屬性。下圖有他們的相同點和不同點:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Consoleapplication2{ public class Employee { public string FirstName; public string Lastname; public string CityOfBirth; /// <summary> /// 創建索引 /// </summary> /// <param name="index"></param> /// <returns></returns> public string this[int index] { set { switch (index) { case 0: FirstName = value; break; case 1: Lastname = value; break; case 2: CityOfBirth = value; break; default: throw new ArgumentOutOfRangeException("index"); } } get { switch (index) { case 0: return FirstName; case 1: return Lastname; case 2: return CityOfBirth; default: throw new ArgumentOutOfRangeException("index"); } } } }}
新聞熱點
疑難解答