淺析C# 索引器(Indexer)
索引器(Indexer) 允許一個對象可以像數組一樣被索引。當您為類定義一個索引器時,該類的行為就會像一個 虛擬數組(virtual array) 一樣。您可以使用數組訪問運算符([ ])來訪問該類的實例。
語法
一維索引器的語法如下:
element-type this[int index]
{
// get 訪問器
get
{
// 返回 index 指定的值
}
// set 訪問器
set
{
// 設置 index 指定的值
}
}
索引器(Indexer)的用途
索引器的行為的聲明在某種程度上類似于屬性(property)。就像屬性(property),您可使用 get 和 set 訪問器來定義索引器。但是,屬性返回或設置一個特定的數據成員,而索引器返回或設置對象實例的一個特定值。換句話說,它把實例數據分為更小的部分,并索引每個部分,獲取或設置每個部分。
定義一個屬性(property)包括提供屬性名稱。索引器定義的時候不帶有名稱,但帶有 this 關鍵字,它指向對象實例。下面的實例演示了這個概念:
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index]
{
get
{
string tmp;
if( index >= 0 && index <= size-1 )
{
tmp = namelist[index];
}
else
{
tmp = "";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for ( int i = 0; i < IndexedNames.size; i++ )
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}
當上面的代碼被編譯和執(zhí)行時,它會產生下列結果:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
重載索引器(Indexer)
索引器(Indexer)可被重載。索引器聲明的時候也可帶有多個參數,且每個參數可以是不同的類型。沒有必要讓索引器必須是整型的。C# 允許索引器可以是其他類型,例如,字符串類型。
下面的實例演示了重載索引器:
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
{
namelist[i] = "N. A.";
}
}
public string this[int index]
{
get
{
string tmp;
if( index >= 0 && index <= size-1 )
{
tmp = namelist[index];
}
else
{
tmp = "";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
public int this[string name]
{
get
{
int index = 0;
while(index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
// 使用帶有 int 參數的第一個索引器
for (int i = 0; i < IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}
// 使用帶有 string 參數的第二個索引器
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}
}
}
當上面的代碼被編譯和執(zhí)行時,它會產生下列結果:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
2
以上就是淺析C# 索引器(Indexer)的詳細內容,更多關于C# 索引器(Indexer)的資料請關注腳本之家其它相關文章!
相關文章
在類庫或winform項目中打開另一個winform項目窗體的方法
這篇文章主要介紹了在類庫或winform項目中打開另一個winform項目窗體的方法,可以實現Winform項目間窗體的調用,在進行Winform項目開發(fā)中非常具有實用價值,需要的朋友可以參考下2014-11-11
C#中DataSet,DataTable,DataView的區(qū)別與用法
這篇文章介紹了C#中DataSet,DataTable,DataView的區(qū)別與用法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05

