概念
索引器(Indexer) 允許類中的物件可以像陣列那樣方便、直觀的被參考,當為類定義一個索引器時,該類的行為就會像一個 虛擬陣列(virtual array) 一樣,
索引器可以有引數串列,且只能作用在實體物件上,而不能在類上直接作用,
可以使用陣列訪問運算子([ ])來訪問該類的實體,
索引器的行為的宣告在某種程度上類似于屬性(property),屬性可使用 get 和 set 訪問器來定義索引器,但是屬性回傳或設定的是一個特定的資料成員,而索引器回傳或設定物件實體的一個特定值,
定義一個一維陣列的索引器:
element-type this[int index]
{
// get 訪問器
get
{
// 回傳 index 指定的值
}
// set 訪問器
set
{
// 設定 index 指定的值
}
}
提示:索引器必須以this關鍵字定義,this 是類實體化之后的物件
實體:
using System;
namespace C_Pro
{
public class Student
{
private string name;
private string grade;
public string Name
{
get {return name; }
set {name = value; }
}
public string Grade
{
get {return grade; }
set {grade = value; }
}
// 定義索引器
public string this[int index]
{
get
{
if (index == 0) return name;
else if (index == 1) return grade;
else return null;
}
set
{
if (index == 0) name = value;
else if (index == 1) grade = value;
}
}
static void Main(string[] args)
{
Student s = new Student();
s[0] = "Jeson";
s[1] = "First-year";
Console.WriteLine(s.Name);
Console.WriteLine(s.Grade);
Console.ReadKey();
}
}
}
運行后結果:
Jeson First-year
多載索引器
索引器(Indexer)可被多載,索引器宣告的時候也可帶有多個引數,且每個引數可以是不同的型別,沒有必要讓索引器必須是整型的,C# 允許索引器可以是其他型別,例如,字串型別,
using System;
namespace C_Pro
{
public class IndexedNames
{
private string[] namelist = {"a", "b", "c", "d"};
// 輸入namelist的index回傳對應的值
public string this[int index]
{
get
{
return namelist[index];
}
set
{
namelist[index] = value;
}
}
// 輸入namelist的值,回傳對應的索引
public int this[string name]
{
get
{
for (int i=0; i<namelist.Length; i++)
{
if (namelist[i] == name) return i;
}
return -1;
}
}
static void Main(string[] args)
{
IndexedNames name = new IndexedNames();
Console.WriteLine(name[1]);
Console.WriteLine(name["a"]);
}
}
}
運行后結果:
b 0
索引器與陣列的區別:
- 索引器的索引值(Index)型別不限定為整數,用來訪問陣列的索引值(Index)一定為整數,而索引器的索引值型別可以定義為其他型別,
- 索引器允許多載, 一個類不限定為只能定義一個索引器,只要索引器的函式簽名不同,就可以定義多個索引器,可以多載它的功能,
- 索引器不是一個變數,索引器沒有直接定義資料存盤的地方,而陣列有,索引器具有Get和Set訪問器,
索引器與屬性的區別:
- 索引器以函式簽名方式 this 來標識,而屬性采用名稱來標識,名稱可以任意,
- 索引器可以多載,而屬性不能多載,
- 索引器不能用static 來進行宣告,而屬性可以,索引器永遠屬于實體成員,因此不能宣告為static,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/31.html
標籤:C#
上一篇:C#數字轉字母,ASCII碼轉換
