轉自 https://www.cnblogs.com/lxblog/p/3940261.html
1、索引器(Indexer):
索引器允許類或者結構的實例按照與數組相同的方式進行索引。索引器類似於屬性,不同之處在於他們的訪問采用參數。
最簡單的索引器的使用
/// <summary>
/// 最簡單的索引器
/// </summary>
public class IDXer
{
private string[] name=new string[10];
//索引器必須以this關鍵字定義,其實這個this就是類實例化之后的對象
public string this[int index]
{
get
{
return name[index];
}
set
{
name[index] = value;
}
}
}
public class Program
{
static void Main(string[] args)
{
//最簡單索引器的使用
IDXer indexer = new IDXer();
//“=”號右邊對索引器賦值,其實就是調用其set方法
indexer[0] = "張三";
indexer[1] = "李四";
//輸出索引器的值,其實就是調用其get方法
Console.WriteLine(indexer[0]);
Console.WriteLine(indexer[1]);
Console.ReadKey();
}
}
2、索引器與數組的區別:
- 索引器的索引值(Index)類型不限定為整數:
用來訪問數組的索引值(Index)一定為整數,而索引器的索引值類型可以定義為其他類型。
- 索引器允許重載
一個類不限定為只能定義一個索引器,只要索引器的函數簽名不同,就可以定義多個索引器,可以重載它的功能。
- 索引器不是一個變量
索引器沒有直接定義數據存儲的地方,而數組有。索引器具有Get和Set訪問器。
3、索引器與屬性的區別:
- 索引器以函數簽名方式 this 來標識,而屬性采用名稱來標識,名稱可以任意
- 索引器可以重載,而屬性不能重載。
- 索引器不能用static 來進行聲明,而屬性可以。索引器永遠屬於實例成員,因此不能聲明為static。
以字符串作為下標,對索引器進行存取:
//以字符串為下標的索引器
public class IDXer2
{
private Hashtable name = new Hashtable();
//以字符串為下標的索引器
public string this[string index]
{
get
{
return name[index].ToString();
}
set
{
name.Add(index, value);
}
}
}
public class Program
{
static void Main(string[] args)
{
//以字符串為下標的索引器
IDXer2 indexer2 = new IDXer2();
indexer2["A01"] = "張三";
indexer2["A02"] = "李四";
Console.WriteLine(indexer2["A01"]);
Console.WriteLine(indexer2["A02"]);
Console.ReadKey();
}
}
多參數索引器及索引器的重載
/// <summary>
/// 成績類
/// </summary>
public class Scores
{
/// <summary>
/// 學生姓名
/// </summary>
public string StuName { get; set; }
/// <summary>
/// 課程ID
/// </summary>
public int CourseId { get; set; }
/// <summary>
/// 分數
/// </summary>
public int Score { get; set; }
}
/// <summary>
/// 查找成績類(索引器)
/// </summary>
public class FindScore
{
private List<Scores> listScores;
public FindScore()
{
listScores = new List<Scores>();
}
//索引器 通過名字&課程編號查找和保存成績
public int this[string stuName, int courseId]
{
get
{
Scores s = listScores.Find(x => x.StuName == stuName && x.CourseId == courseId);
if (s != null)
{
return s.Score;
}
else
{
return -1;
}
}
set
{
listScores.Add(new Scores() { StuName = stuName, CourseId = courseId, Score = value });
}
}
//索引器重載,根據名字查找所有成績
public List<Scores> this[string stuName]
{
get
{
List<Scores> tempList = listScores.FindAll(x => x.StuName == stuName);
return tempList;
}
}
}
static void Main(string[] args)
{
//多參數索引器和索引器重載
FindScore fScore = new FindScore();
fScore["張三", 1] = 98;
fScore["張三", 2] = 100;
fScore["張三", 3] = 95;
fScore["李四", 1] = 96;
//查找 張三 課程編號2 的成績
Console.WriteLine("李四 課程編號2 成績為:" + fScore["李四", 1]);
//查找所有張三的成績
List<Scores> listScores = fScore["張三"];
if (listScores.Count > 0)
{
foreach (Scores s in listScores)
{
Console.WriteLine(string.Format("張三 課程編號{0} 成績為:{1}", s.CourseId, s.Score));
}
}
else
{
Console.WriteLine("無該學生成績單");
}
Console.ReadKey();
}

