C# - インデクサー
インデクサー 配列などのオブジェクトにインデックスを付けることができます。クラスのインデクサーを定義すると、このクラスは 仮想配列 と同じように動作します .その後、配列アクセス演算子 ([ ]) を使用して、このクラスのインスタンスにアクセスできます。
構文
1 次元インデクサーには次の構文があります −
element-type this[int index] {
// The get accessor.
get {
// return the value specified by index
}
// The set accessor.
set {
// set the value specified by index
}
}
インデクサーの使用
インデクサーの動作の宣言は、ある程度プロパティに似ています。プロパティと同様に、 get を使用します そしてセット インデクサーを定義するためのアクセサー。ただし、プロパティは特定のデータ メンバーを返したり設定したりしますが、インデクサーはオブジェクト インスタンスから特定の値を返したり設定したりします。つまり、インスタンス データを小さな部分に分割し、各部分にインデックスを付け、各部分を取得または設定します。
プロパティを定義するには、プロパティ名を指定する必要があります。インデクサーは名前ではなく、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();
}
}
}
上記のコードをコンパイルして実行すると、次の結果が生成されます −
Zara Riz Nuha Asif Davinder Sunil Rubic N. A. N. A. N. A.
オーバーロードされたインデクサー
インデクサーは過負荷になる可能性があります。インデクサーは複数のパラメーターで宣言することもでき、各パラメーターは異なる型になる場合があります。インデックスが整数である必要はありません。 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";
//using the first indexer with int parameter
for (int i = 0; i < IndexedNames.size; i++) {
Console.WriteLine(names[i]);
}
//using the second indexer with the string parameter
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
}
}
}
上記のコードをコンパイルして実行すると、次の結果が生成されます −
Zara Riz Nuha Asif Davinder Sunil Rubic N. A. N. A. N. A. 2
C言語