zoukankan      html  css  js  c++  java
  • C#循环语句 -0012

    C#提供了4种不同的循环语句(for, while, do...while和foreach)。

    for 循环

    C#的for循环提供了一种循环机制,根据指定的判断条件是否为true决定是否进入下一次循环。通常格式如下:

    for ([initializer]; [condition]; [iterator])
    {
        statement(s);
    }
    

    for循环被称为前测循环(pretest loop)因为它在执行循环体内的语句前,会先判断condition是否成立。因此如果condition为false的话,循环体将完全不执行。

    while循环

    跟for循环一样,while循环也是一个前测循环。语法很相似,但while循环只需要一个表达式:

    while(condition)
    {
    	statement(s);
    }
    

    while循环更多地用于你事先不知道执行次数的情况下,去重复执行一段语句。

    通常在while循环体内运算到某次循环的时候,就会修改condition计算出来的值,使得整个循环体能够结束。

    bool condition = false;
    while (!condition)
    {
        // This loop spins until the condition is true.
    	DoSomeWork();
        // assume CheckCondition() returns a bool, it will return true at a time then end the loop.
    	condition = CheckCondition(); 
    }
    

    do...while循环

    do...while循环是while循环的后测(post-test)版本。会先执行循环体,然后再检测condition是否为true。因此do...while循环适用至少执行一次的情况:

    bool condition;
    do
    {
    	// This loop will at least execute once, even if Condition is false.
    	MustBeCalledAtLeastOnce();
    	condition = CheckCondition();
    } while (condition);
    

    foreach循环

    foreach循环可以迭代集合中的每一项。(集合是一组对象,集合里的对象必须实现IEnumerable接口)

    IList<int> listOfInts = new List<int>() { 1, 2, 3, 4, 5, 6 };
    
    foreach (var item in listOfInts)
    {
       Console.WriteLine(item);
    }
    

      

    一个非常重要的点是,在foreach循环里所有元素都是只读的,你不能进行任何修改操作,像下面这样的代码会提示编译错误:

    foreach (int item in listOfInts)
    {
    	item++; 
    	Console.WriteLine(temp);
    }
    

      error CS1656: Cannot assign to 'item' because it is a 'foreach iteration variable'

  • 相关阅读:
    CSS cursor 属性笔记
    sql 不等于 <>
    去掉时间中的时分秒
    ref 和 out区别
    关于闭包(未完待续)
    面向对象——多态(摘)
    SQL Service 数据库 基本操作 视图 触发器 游标 存储过程
    遍历winform 页面上所有的textbox控价并赋值string.Empty
    关于Html 和Xml 区别(备忘)
    python之面向对象进阶
  • 原文地址:https://www.cnblogs.com/codesee/p/13033225.html
Copyright © 2011-2022 走看看