实现IEnumberable接口和IEnumberator

时间:2022-07-29 06:00:51
 class BookEnum : IEnumerator  //实现foreach语句内部,并派生
{ public Book[] _book; //实现数组 int position = -;//设置“指针” public BookEnum(Book[] list)
{ _book = list; //实现list } public bool MoveNext()//实现向前移动
{ position++; //位置增加 return (position < _book.Length); //返回布尔值 } public void Reset() //位置重置
{ position = -; }//重置指针为-1 public object Current //实现接口方法
{ get
{ try
{ return _book[position]; //返回对象 } catch (IndexOutOfRangeException) //捕获异常
{ throw new InvalidOperationException(); //抛出异常信息 } } } } public class Book : IEnumerable
{ public string Name; public string Price; public Book(string name, string price)
{ Name = name; Price = price; } private Book[] book; public Book(Book[] array) //
{ book = array; } public IEnumerator GetEnumerator() //实现接口
{ return new BookEnum(book); //返回方法
}
} public partial class MainWindow : Window
{
public Student stu;
public MainWindow()
{
InitializeComponent();
Book[] book = new Book[]
{ new Book("水浒",""), new Book("三国",""), new Book("西游","") }; foreach (Book p in book)
{ this.textBox2.Text+="书的名字:" + p.Name + ";价格: " + p.Price; } }

相关文章