class BookEnum : IEnumerator //实现foreach语句内部,并派生 { public Book[] _book; //实现数组 int position = -1;//设置“指针” public BookEnum(Book[] list) { _book = list; //实现list } public bool MoveNext()//实现向前移动 { position++; //位置增加 return (position < _book.Length); //返回布尔值 } public void Reset() //位置重置 { position = -1; }//重置指针为-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[3] { new Book("水浒","21"), new Book("三国","21"), new Book("西游","21") }; foreach (Book p in book) { this.textBox2.Text+="书的名字:" + p.Name + ";价格: " + p.Price; } }
时间: 2024-10-07 18:26:12