本文实例讲述了C#使用foreach循环遍历数组的方法。分享给大家供大家参考,具体如下: using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class Progra
本文实例讲述了C#使用foreach循环遍历数组的方法。分享给大家供大家参考,具体如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//声明数组. 第一种方法. 声明并分配元素大小.
int[] Myint = new int[30];
Myint[0] = 30;
Myint[1] = 50;
// 以此类推, 起始下标为0
//-------------------------------
// 声明数组,第二种方法, 声明并直接赋值,没有指定元素大小.
int[] Myint1 = { 20,10,50,65,18,90};
//------------------------------------------
//声明数组,第三种方法, 声明并分配大小,且赋值.
int[] i = new int[5] { 10, 20, 30, 40, 50 };
// -----------------------------------------------
// foreach循环遍历数组..
int[] Sum = new int[50];
Random rd = new Random();
// 先用for循环给数组取随机数.
for (int s = 0; s <= Sum.Length - 1; s++) // Sum.Length是数组的一个属性,Length代表数组的长度
{
Sum[s] = rd.Next(100);
}
// 遍历数组输出
foreach (int t in Sum)
{
Console.WriteLine(t);
}
}
}
}
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#遍历算法与技巧总结》、《C#程序设计之线程使用技巧总结》、《C#操作Excel技巧总结》、《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》
希望本文所述对大家C#程序设计有所帮助。
