声明索引的语法如此下,请注意以下几点:
声明索引类似于声明属性。下图有他们的相同点和不同点:
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"); } } } }}
新闻热点
疑难解答