一、自定义集合定义
1、通过继承IEnumerable, IEnumerator接口实现自定义集合;
2、需要实现IEnumerable.GetEnumerator()方法用来返回循环访问集合的枚举器,主要是迭代集合时使用;
3、实现IEnumerator接口的Current属性、MoveNext()、Reset()方法:
Current属性:获取集合中当前位置的元素,
MoveNext():迭代集合中的下一个元素,
Reset():设置初始位置,位置位于集合第一个元素之前;
二、自定义集合示例:
1、自定义集合:
internal class JHStu : IEnumerable, IEnumerator
{
private Student[] students;
public JHStu(Student[] stus)
{
students = new Student[stus.Length];
for (int i = 0; i < stus.Length; i++)
{
students[i] = stus[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)this;
}
int position = -1;
public object Current => students[position];
public bool MoveNext()
{
position++;
return position<students.Length;
}
public void Reset()
{
position = -1;
}
}
2、使用自定义集合:
class Pro
{
public static void Main()
{
Student[] stus = new Student[3] {
new Student(1,"xiaoli"),
new Student(2,"xiaohua"),
new Student(3,"xiaohong")
};
JHStu stujh = new JHStu(stus);
foreach (Student student in stus)
{
Console.WriteLine("{0}:{1}", student.Id, student.Name);
}
foreach (Student stu in stujh)
{
Console.WriteLine(stujh.Current);
}
}
}
internal class Student
{
public int Id { get; set; }
public string? Name { get; set; }
public Student(int id, string name)
{
Id = id;
Name = name;
}
}
三、索引器的使用
索引器的声明方式与属性相似,区别是索引器的声明需要以this定义参数
不能为静态static
声明格式:修饰符 类型 this[]
{
get{ }
set{ }
}
示例代码:
public string this[int index]
{
get => students[index].Name;
set => students[index].Name = value;
}
使用:
stujh[0] = "Auston";