C# 枚举
2018-01-22 17:10 更新
C# 枚举
枚举器是值的列表上的只读,只向前的光标。
枚举器是实现以下任一接口的对象:
System.Collections.IEnumerator System.Collections.Generic.IEnumerator<T>
foreach 语句可以遍历可枚举对象。
例子
可枚举对象实现 IEnumerable 或 IEnumerable<T> 。
可枚举对象有一个名为GetEnumerator的方法,返回一个枚举器。
IEnumerator 和 IEnumerable 在 System.Collections 中定义。
IEnumerator< T> 和 IEnumerable< T> 在 System.Collections.Generic 中定义。
下面是使用foreach语句对字符进行迭代的高级方法:
foreach (char c in "www.w3cschool.cn"){
Console.WriteLine (c);
}
这里是低层次的遍历字符的方法,而不使用foreach语句:
using (var enumerator = "www.w3cschool.cn".GetEnumerator())
while (enumerator.MoveNext()) {
var element = enumerator.Current;
Console.WriteLine (element);
}
集合初始化程序
您可以在一个步骤中实例化和填充可枚举对象。
例如:
using System.Collections.Generic;
...
List<int> list = new List<int> {1, 2, 3};
为了使上面的代码起作用,enumerable对象必须实现System.Collections.IEnumerable接口,并且它具有一个Add方法,该方法具有适当数量的调用参数。
以上内容是否对您有帮助:
← C# 异常

免费 AI IDE


更多建议: