HOW TO:使用 C# 索引子
更新:2007 年 11 月
Visual C++ 不包含索引子 (Indexer),但是有索引屬性。若要使用 C# 索引子,請將索引子當做索引屬性來存取。
如需索引子的詳細資訊,請參閱:
範例
下列 C# 程式會定義索引子。
// consume_cs_indexers.cs
// compile with: /target:library
using System;
public class IndexerClass {
private int [] myArray = new int[100];
public int this [int index] { // Indexer declaration
get {
// Check the index limits.
if (index < 0 || index >= 100)
return 0;
else
return myArray[index];
}
set {
if (!(index < 0 || index >= 100))
myArray[index] = value;
}
}
}
/*
// code to consume the indexer
public class MainClass {
public static void Main() {
IndexerClass b = new IndexerClass();
// Call indexer to initialize elements 3 and 5
b[3] = 256;
b[5] = 1024;
for (int i = 0 ; i <= 10 ; i++)
Console.WriteLine("Element #{0} = {1}", i, b[i]);
}
}
*/
這個 Visual C++ 程式會使用此索引子。
// consume_cs_indexers_2.cpp
// compile with: /clr
#using "consume_cs_indexers.dll"
using namespace System;
int main() {
IndexerClass ^ ic = gcnew IndexerClass;
ic->default[0] = 21;
for (int i = 0 ; i <= 10 ; i++)
Console::WriteLine("Element #{0} = {1}", i, ic->default[i]);
}
Element #0 = 21 Element #1 = 0 Element #2 = 0 Element #3 = 0 Element #4 = 0 Element #5 = 0 Element #6 = 0 Element #7 = 0 Element #8 = 0 Element #9 = 0 Element #10 = 0