在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
用foreach遍历访问的对象需要实现 IEnumerable 接口或声明 GetEnumerator 方法的类型。
namespace System.Collections { // Summary: // Exposes the enumerator, which supports a simple iteration over a non-generic // collection. [ComVisible(true)] [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")] public interface IEnumerable { // Summary: // Returns an enumerator that iterates through a collection. // // Returns: // An System.Collections.IEnumerator object that can be used to iterate through // the collection. [DispId(-4)] IEnumerator GetEnumerator(); } } IEnumerator接口: namespace System.Collections { // Summary: // Supports a simple iteration over a nongeneric collection. [ComVisible(true)] [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")] public interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); } } 示例: namespace ForeachDemo { public class MySplit : IEnumerable { private string[] elements; public MySplit(string source,char[] delimiters) { elements = source.Split(delimiters); } public string[] Elements { get { return elements; } } IEnumerator IEnumerable.GetEnumerator() { return new MyEnumerator(this); } } public class MyEnumerator : IEnumerator { private int position = -1; private MySplit t; public MyEnumerator(MySplit t) { this.t = t; } public bool MoveNext() { if (position<t.Elements.Length - 1) { position++; return true; } else { return false; } } public void Reset() { position = -1; } object IEnumerator.Current { get { try { return t.Elements[position]; } catch(IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } class Program { static void Main(string[] args) { MySplit mysplit = new MySplit("i am a good student.",new char[]{' '}); foreach(string item in mysplit) { Console.WriteLine(item); } Console.ReadLine(); } } } 输出:
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论