1. 程式人生 > >C#for(;;)是什麽意思?

C#for(;;)是什麽意思?

str void 跳出循環 linq args 常見 我們 也不會 generic

一,正常for循環我們都接觸過很多,如下,我們都理解

           int[] tt = {1,2,3,4,5,6 };
            for (int i = 1; i < 6; i++)
            {
                Console.WriteLine(tt[i]);
            }    

二,但是for(;;)實際上它的含義是什麽呢?

含義: for後的圓括號中,第一個分號前的內容是執行第一次循環前執行的,第二個分號前的內容是每次執行前都要判斷的(如果該處表達式的值為真,那麽執行循環體,如果為假,那麽就跳出循環體)

三,是不是覺得寫到這裏大家覺得那麽常見的都還要介紹?那我們來點擴展,如下代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace W
{
    class Program
    {
        static void Main(string[] args)
        {
            int t2 = 0;
            int t1 = 0;
            for (Demo.First(ref t1); Demo.Scend(t1, ref
t2); ) { Console.WriteLine(t2); } } } public class Demo { public static int j = 5; public static bool First(ref int t1) { t1 = 1; return false; } public static bool Scend(int
t1,ref int t2) { if (j > 0) { j = j - t1; t2 = j; return true; } else { return false; } } } }

三,在上述代碼中我們看到for (Demo.First(); Demo.Scend(1,ref te); )是在分號調用兩個方法,是不是跟平常使用的不一樣??那為什麽可以這樣用呢?我們根據for(;;)的含義來解析。

1,第一個分號前的內容是執行第一次循環前執行的,而第一個分號不會判斷true和false,所以當定義返回false時也不會跳出循環

2,第二個分號前的內容是每次執行前都要判斷的(如果該處表達式的值為真,那麽執行循環體,如果為假,那麽就跳出循環體)

C#for(;;)是什麽意思?