索引器允许对象被索引,例如:数组。 当为类定义索引器时,此类与虚拟数组类似。可以使用数组访问运算符([]
)访问此类的实例。
一维索引器的语法如下:
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