C#初學(xué)——C#索引(index)
通過(guò)C#的一些學(xué)習(xí)內(nèi)容,我看到了C#索引的使用,感覺(jué)自己沒(méi)什么概念,就學(xué)習(xí)了下。感覺(jué)比較好,適合初學(xué)者。
下面是貼出來(lái)的代碼:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace index
- {
- class Worker
- {
- public string LastName;
- public string FirstName;
- public string MyBirth;
- public string this[int index]
- {
- set
- {
- switch (index)
- {
- case 0: LastName = value;
- break;
- case 1: FirstName = value;
- break;
- case 2: MyBirth = value;
- break;
- default:
- throw new ArgumentOutOfRangeException("index");
- break;
- }
- }
- get
- {
- switch(index)
- {
- case 0 : return LastName;
- case 1 : return FirstName;
- case 2 : return MyBirth;
- default :
- throw new ArgumentOutOfRangeException("index");
- break;
- }
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Worker a = new Worker();
- Console.WriteLine("print the value:{0},{1},{2}",a[0],a[1],a[2]);
- Console.WriteLine("please print your last name");
- a[0] = Console.ReadLine();
- Console.WriteLine("please print your first name");
- a[1] = Console.ReadLine();
- Console.WriteLine("please print your birthday");
- a[2] = Console.ReadLine();
- Console.WriteLine("Now,your name is {0},{1},and your birth is {2}",a[0],a[1],a[2]);
- }
- }
- }
首先什么是C#索引呢?
書(shū)上說(shuō)它是一組get和set訪問(wèn)器,我個(gè)人就直接這么認(rèn)為就是獲值或設(shè)值的概念。(可能是錯(cuò)誤的啊,呵呵,理論太差,剛看的)。
怎樣聲明C#索引呢?
他的語(yǔ)法是如下:
要注意下面幾點(diǎn):a:索引沒(méi)有名稱(chēng),它是通過(guò)關(guān)鍵字this。
b:參數(shù)列表在方括號(hào)里面。
c:參數(shù)列表至少必須聲明一個(gè)參數(shù)。
- ReturnType this [type param1,...]
- {
- get
- {
- ...
- }
- set
- {
- ...
- }
- }
【編輯推薦】