22.自定义容器支持for循环
22.1 题目
C#中如何让自定义容器类能够使用for循环遍历?(通过 类对象[索引] 的形式遍历)
22.2 深入解析
通过在类中实现索引器实现。以下是具体实现步骤和示例代码:
实现步骤
- 定义索引器:在自定义容器类中定义一个索引器,用于根据索引访问容器中的元素。
- 实现必要的方法和属性:通常需要实现
Count属性来返回容器中元素的数量,以便for循环使用。
示例代码
using System;
public class CustomContainer<T>
{
private T[] items;
private int count;
public CustomContainer(int size)
{
items = new T[size];
count = size;
}
// 索引器的实现
public T this[int index]
{
get
{
if (index < 0 || index >= count)
{
throw new IndexOutOfRangeException("索引超出范围");
}
return items[index];
}
set
{
if (index < 0 || index >= count)
{
throw new IndexOutOfRangeException("索引超出范围");
}
items[index] = value;
}
}
// 容器中元素的数量
public int Count
{
get { return count; }
}
}
class Program
{
static void Main()
{
CustomContainer<int> container = new CustomContainer<int>(5);
// 添加元素到容器中
for (int i = 0; i < container.Count; i++)
{
container[i] = i * 10;
}
// 使用 for 循环遍历容器
for (int i = 0; i < container.Count; i++)
{
Console.WriteLine(container[i]);
}
}
}
解释
- 索引器:通过
this[int index]定义索引器,使得可以使用container[index]的形式访问和设置容器中的元素。 - Count属性:实现
Count属性,返回容器中元素的数量,以便在for循环中使用。 - for循环遍历:在示例中,
for循环利用索引器遍历并输出容器中的元素。
通过实现索引器,自定义容器类可以方便地使用索引访问元素,从而支持for循环遍历。
22.3 答题示例
“在C#中让自定义容器支持
for循环遍历需实现索引器(Indexer)和Count属性:
- 索引器定义:通过
this[int index]语法实现读写访问,例如:public T this[int index] { get { /* 索引获取逻辑 */ } set { /* 索引设置逻辑 */ } }- 边界校验:需处理索引越界(如抛出
IndexOutOfRangeException)。- Count属性:提供容器元素数量,供
for循环条件判断:public int Count { get; }- 使用示例:
CustomContainer<int> list = new(5); for (int i = 0; i < list.Count; i++) { list[i] = i * 10; // 通过索引器赋值 }该方式通过索引器模拟数组访问行为,使
for循环可直接通过索引遍历元素。”
22.4 关键词联想
索引器(Indexer)- get/set 访问器
- Count 属性
- IndexOutOfRangeException
泛型容器(Generic Container)- 索引器(
this[]) 遍历接口(Traversal Interface)
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 785293209@qq.com