通過昨天goody的推薦,到葉子文文上面看了下C#的一些學習内容,感覺比較好,适合初學者。 我簡單的過了遍,看到了索引的使用,感覺自己沒什麼概念,就學習了下。 下面是貼出來的代碼:
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]);
}
}
}
首先什麼是索引呢? 書上說它是一組get和set通路器,我個人就直接這麼認為就是獲值或設值的概念。(可能是錯誤的啊,呵呵,理論太差,剛看的)。 怎樣聲明索引呢? 他的文法是如下: 要注意下面幾點:a:索引沒有名稱,它是通過關鍵字this。 b:參數清單在方括号裡面。 c:參數清單至少必須聲明一個參數。
ReturnType this [type param1,...]
{
get
{
...
}
set
{
...
}
}
轉載于:https://blog.51cto.com/jayai/188731