//索引器:字段包含数组,为了简单访问数组字段,C#提供了索引器
// 访问修饰符 类型 this[int index,...,...]
using System;
namespace IndexerApplication
{
class IndexedNames
{
class IndexTest
{
public int[] Id = new int[3];
public string[] Name = new string[3];
//Id的索引器
public int this[int index]
{
get
{
return Id[index];
}
set
{
Id[index] = value;
}
}
//Name的索引器
public string this[int index,string name = "name"] /* 再加一个参数对索引器进行重载,定义出一个控制Name字段的索引器 */
{
get
{
return Name[index];
}
set
{
Name[index] = value;
}
}
}
static void Main(string[] args)
{
IndexTest test = new IndexTest();
//访问Id索引器
test[0] = 11;
test[1] = 22;
test[2] = 33;
for (int i = 0; i <= 2; i ++)
{
Console.WriteLine(test[i]);
}
//访问Name索引器
test[0, "name"] = "aa";
test[1, "name"] = "bb";
test[2, "name"] = "cc";
for (int i = 0; i <= 2; i++)
{
Console.WriteLine(test[i,"name"]);
}
}
}
}
// 访问修饰符 类型 this[int index,...,...]
using System;
namespace IndexerApplication
{
class IndexedNames
{
class IndexTest
{
public int[] Id = new int[3];
public string[] Name = new string[3];
//Id的索引器
public int this[int index]
{
get
{
return Id[index];
}
set
{
Id[index] = value;
}
}
//Name的索引器
public string this[int index,string name = "name"] /* 再加一个参数对索引器进行重载,定义出一个控制Name字段的索引器 */
{
get
{
return Name[index];
}
set
{
Name[index] = value;
}
}
}
static void Main(string[] args)
{
IndexTest test = new IndexTest();
//访问Id索引器
test[0] = 11;
test[1] = 22;
test[2] = 33;
for (int i = 0; i <= 2; i ++)
{
Console.WriteLine(test[i]);
}
//访问Name索引器
test[0, "name"] = "aa";
test[1, "name"] = "bb";
test[2, "name"] = "cc";
for (int i = 0; i <= 2; i++)
{
Console.WriteLine(test[i,"name"]);
}
}
}
}