1.创建array & foreach语句
1. public class Student 2. { 3. public Student(int stuID) 4. { 5. this.stuID = stuID; 6. } 7. public override string ToString() 8. { 9. return stuID.ToString(); 10. } 11. private int stuID; 12. } 13. 14. class Program 15. { 16. static void Main(string[] args) 17. { 18. int[] array = new int[5]; 19. Student[] student = new Student[2]; 20. for(int i = 0; i < student.Length; i++) 21. { 22. student[i] = new Student(i + 5); 23. } 24. foreach( int i in array ) 25. { 26. Console.WriteLine(i.ToString()); 27. } 28. foreach( Student stu in student ) 29. { 30. Console.WriteLine(stu.ToString()); 31. } 32. 33. } 34. }
结果为:
2.the params Keyword
可以不显式地创建数组,而是直接将值传递给带有params参数的函数。
1 class Program 2 { 3 static public void disPlay(params int[] values) 4 { 5 foreach(int i in values) 6 { 7 Console.WriteLine("the value is {0}", i); 8 } 9 } 10 static void Main(string[] args) 11 { 12 Program.disPlay(1, 2, 3, 4); 13 int[] temp = { 5, 6, 7, 8 }; 14 Program.disPlay(temp); 15 16 } 17 }
结果为:
3.多维数组
c#中jagged array的创建与使用与c++中类似。
4.the bound of an array
重载createInstance。
1 class Program 2 { 3 public class setArrBounds 4 { 5 public static void creatArr() 6 { 7 int[] lengthOfArr = { 2, 4 };//二维数组,长度分别为2,4 8 int[] lowerBound = { 3, 5 };//每维的下界分别为3,5 9 Array array = Array.CreateInstance(typeof(int),lengthOfArr,lowerBound); 10 //显示每个维度的上下界 11 Console.WriteLine("bounds: Lower upper"); 12 for (int i = 0; i < array.Rank; i++) 13 { 14 int j = i+1; 15 Console.WriteLine("维度{0}: {1} {2}", j, array.GetLowerBound(i), array.GetUpperBound(i)); 16 } 17 } 18 } 19 20 static void Main(string[] args) 21 { 22 setArrBounds.creatArr(); 23 24 } 25 }
结果为:
over