推荐答案
// www.javascriptcn.com code example
class MyCollection
{
private string[] data = new string[10];
// 定义索引器
public string this[int index]
{
get
{
if (index >= 0 && index < data.Length)
return data[index];
else
throw new IndexOutOfRangeException();
}
set
{
if (index >= 0 && index < data.Length)
data[index] = value;
else
throw new IndexOutOfRangeException();
}
}
}
class Program
{
static void Main()
{
MyCollection collection = new MyCollection();
collection[0] = "Hello";
collection[1] = "World";
Console.WriteLine(collection[0]); // 输出: Hello
Console.WriteLine(collection[1]); // 输出: World
}
}本题详细解读
索引器的概念
索引器(Indexer)是C#中的一种特殊成员,允许类的实例像数组一样通过索引访问。索引器使得对象可以像数组一样使用[]运算符来访问其内部的数据。索引器通常用于封装集合类,使得访问集合中的元素更加直观和方便。
索引器的语法
索引器的定义类似于属性,但它使用this关键字,并且需要指定一个或多个参数。索引器的语法如下:
// www.javascriptcn.com code example
public returnType this[parameterType parameter]
{
get
{
// 返回指定索引的值
}
set
{
// 设置指定索引的值
}
}returnType:索引器的返回类型,表示通过索引访问时返回的数据类型。parameterType:索引参数的类型,通常是int或string。parameter:索引参数,用于指定要访问的元素。
索引器的使用
索引器可以像数组一样使用[]运算符来访问或设置对象中的元素。例如:
MyCollection collection = new MyCollection(); collection[0] = "Hello"; // 使用索引器设置值 string value = collection[0]; // 使用索引器获取值
索引器的优点
- 封装性:索引器可以隐藏内部数据结构的实现细节,提供统一的访问接口。
- 灵活性:索引器可以支持多种类型的索引参数,如整数、字符串等。
- 易用性:索引器使得对象的使用方式更加直观,类似于数组的访问方式。
索引器的注意事项
- 索引器的参数:索引器可以有一个或多个参数,但通常使用一个参数来表示索引。
- 索引器的重载:一个类可以定义多个索引器,只要它们的参数类型或数量不同即可。
- 索引器的异常处理:在索引器的实现中,通常需要处理索引越界的情况,以避免程序崩溃。
示例代码解析
在示例代码中,MyCollection类定义了一个索引器,允许通过整数索引访问内部的string数组。索引器的get和set访问器分别用于获取和设置数组中的元素。在Main方法中,我们创建了MyCollection的实例,并通过索引器访问和修改数组中的元素。
// www.javascriptcn.com code example
class MyCollection
{
private string[] data = new string[10];
// 定义索引器
public string this[int index]
{
get
{
if (index >= 0 && index < data.Length)
return data[index];
else
throw new IndexOutOfRangeException();
}
set
{
if (index >= 0 && index < data.Length)
data[index] = value;
else
throw new IndexOutOfRangeException();
}
}
}在这个示例中,索引器确保了在访问数组时不会越界,如果索引超出范围,则会抛出IndexOutOfRangeException异常。