索引器允许对象被索引,例如:数组。 当为类定义索引器时,此类与虚拟数组类似。可以使用数组访问运算符([]
)访问此类的实例。
语法
一维索引器的语法如下:
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
和set
访问器定义索引器。但是,属性返回或设置特定的数据成员,而索引器从对象实例返回或设置特定值。 换句话说,它将实例数据分解成较小的部分,并对每个部分进行索引,获取或设置每个部分。
定义属性涉及提供属性名称。索引器不是用名称定义的,而是使用这个引用对象实例的关键字。以下示例演示了以下概念:
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] = "Maxsu";
names[1] = "Sukida";
names[2] = "Mark";
names[3] = "Jame";
names[4] = "Davinder";
names[5] = "Lucy";
names[6] = "Lily";
for (int i = 0; i < IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
Maxsu
Sukida
Mark
Jame
Davinder
Lucy
Lily
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] = "Maxsu";
names[1] = "Richer";
names[2] = "Nuber";
names[3] = "DockJ";
names[4] = "Vadder";
names[5] = "Sukida";
names[6] = "Ruby";
//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();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
Maxsu
Richer
Nuber
DockJ
Vadder
Sukida
Ruby
N. A.
N. A.
N. A.
10
上一篇:
C#属性(Properties)
下一篇:
C#委托