索引器
C#中的索引器允许你通过类似于数组的语法来访问对象的元素。它们提供了一种在类或结构中定义和访问元素的方式,就像访问数组或集合的元素一样。
以下是索引器的使用示例:
public class MyCollection
{
private string[] items = new string[5];
// 索引器定义
public string this[int index]
{
get { return items[index]; }
set { items[index] = value; }
}
}
在上面的示例中,MyCollection类定义了一个名为items的私有字符串数组,并通过索引器提供对数组元素的访问。索引器使用整数类型的索引参数,并通过get和set访问器提供对元素的读取和写入操作。
你可以像使用数组一样使用索引器来访问和修改元素:
MyCollection collection = new MyCollection();
collection[0] = "Item 1"; //set
string item = collection[0]; //get
Console.WriteLine(item); // 输出: Item 1
使用索引器的好处是,它们可以为类或结构提供类似于数组的访问方式,使代码更易于阅读和编写。通过索引器,你可以将类的实例视为一个集合,并通过类似于数组的语法来访问和操作元素。
索引器还可以用于实现自定义的集合类或数据结构,使其在使用时更加直观和方便。你可以根据自己的需求定义索引器的行为,并在类中使用索引器来提供更高级的功能,如数据验证、计算或转换。
索引器和属性
- 和属性一样,索引器不用分配内存存储
- 属性表示单独的数据成员
- 索引器表示多个数据成员
- 索引器可以只有一访问器,也可以两个都有
索引器的另一个示例
对于多个string的字段声明索引器的示例:
class Employee{
public string LastName;
public string FirstName;
public string City;
public string this[index]{
set{
switch(index){
case 0:LastName = value;
break;
case 1:FirstName = value;
break;
case 2:City = value;
break;
default:
throw new ArgumentOutOfRangeException("index");
}
}
get{
//.........
}
}
}
索引器重载
当一个类需要通过不同的索引方式来访问和修改数据时,可以使用索引器重载。下面是一个示例,演示如何使用索引器重载来实现对学生数据的访问:
public class StudentCollection
{
private List<string> names = new List<string>();
private List<int> ages = new List<int>();
// 索引器重载1:通过索引访问和修改学生名称
public string this[int index]
{
get { return names[index]; }
set { names[index] = value; }
}
// 索引器重载2:通过学生名称访问和修改学生年龄
public int this[string name]
{
get
{
int index = names.IndexOf(name);
if (index != -1)
return ages[index];
else
return -1;
}
set
{
int index = names.IndexOf(name);
if (index != -1)
ages[index] = value;
}
}
// 添加学生信息
public void AddStudent(string name, int age)
{
names.Add(name);
ages.Add(age);
}
}
在上述示例中,StudentCollection类包含两个字段:names和ages,分别用于存储学生的姓名和年龄。它定义了两个索引器重载,以提供通过索引和姓名两种方式访问学生数据。
第一个索引器重载接受整数类型的索引参数,用于访问和修改names列表中的学生姓名。第二个索引器重载接受字符串类型的索引参数,用于根据学生姓名查找和修改对应的学生年龄。
你可以按照下面的方式使用索引器重载:
StudentCollection students = new StudentCollection();
students.AddStudent("John", 20);
students.AddStudent("Jane", 22);
students[0] = "Mark"; // 修改第一个学生的姓名
students["Jane"] = 23; // 修改名为Jane的学生的年龄
string studentName = students[0]; // 获取第一个学生的姓名
int studentAge = students["Jane"]; // 获取名为Jane的学生的年龄
Console.WriteLine(studentName); // 输出: Mark
Console.WriteLine(studentAge); // 输出: 23
上述示例中,我们通过使用两个不同的索引器重载,可以通过索引和学生姓名两种方式来访问和修改学生数据。这使得代码更加灵活和易用,可以根据不同的需求选择不同的索引方式来操作数据。