标签:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace _05foreach使用 { class Program { static void Main(string[] args) { int[] arr = { 1, 3, 5, 7, 9 }; foreach (var item in arr) { Console.WriteLine(item); } Console.WriteLine("======================"); ArrayList list = new ArrayList() { 5, 6, 7, 3, 89, 4 }; foreach (var item in list) { Console.WriteLine(item); } Console.WriteLine("============================="); List<int> list1 = new List<int>() { 9, 9, 9, 9, 3, 3, 3, 4 }; foreach (var item in list1) //这里的List泛型集合可以用var遍历取值.Dictionary不可以用var去foreach;只能用KeyValuePair<,> { Console.WriteLine(item); } Console.WriteLine("==============================="); Person p = new Person(); for (int i = 0; i < p.Count; i++) { Console.WriteLine(p[i]); } //Person[] ps = new Person[] { new Person(),new Person()}; //数组当然可以用foreach遍历,而不管你是什么数组 // foreach (var item in p) { //foreach被设计用来和可枚举类型一起使用,只要给它的遍历对象是可枚举类型就行。比如数组 //Error:Person类不包含GetEnumerator的公共定义,因此foreach语句不能作用域Person类型的变量 //实际上通过foreach遍历数据,实际上是调用了一个"枚举器"来遍历数据,和foreach一点关系都没有, //foreach只是一个语法上的转化,可以反编译看看IL,实际上还是用GetEnumerator(). //用foreach只是为了降低编码的复杂度 //凡是具有GetEnumerator()这个方法的类型都能用foreach遍历 } Console.ReadKey(); } } public class Person { private string[] name = { "hl", "xzl", "pdh", "zbq" }; public int Count { get { return name.Length; } } public string this[int index] { get { return name[index]; } } public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } }
标签:
原文地址:http://www.cnblogs.com/haust/p/4424688.html