c#中for與foreach的使用


for循環示例:

static void Main(string[] args)
        {
            string[] s = new string[] { "a,b,c,d,e,f,g" };
            for (int i = 0; i < s.Length; i++)
            {
                Console.WriteLine(s[i]);
            }
            Console.ReadKey();
        }

foreach循環示例:

static void Main(string[] args)
        {
            string[] s = new string[] { "a,b,c,d,e,f,g" };
            foreach (string item in s)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }

總結:

for循環需給初值,步長,末值,foreach則不需要,它是自動遍歷集合體中所有值

for循環可用於任何重復行為,foreach循環只能用於遍歷

foreach循環遍歷速度比for循環快


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM