首页 > 编程语言 >C# 学习笔记 - 控制流

C# 学习笔记 - 控制流

时间:2023-07-02 13:12:18浏览次数:56  
标签:语句 Console C# 控制流 笔记 else while WriteLine public

控制流

条件语句、迭代语句、跳转语句和异常处理语句控制程序的执行流。

  • 条件语句使用关键字 if, switch 来决定执行某些语句
  • 迭代语句使用关键字 do, while, for, foreach 和 in 创建一个循环
  • 跳转语句使用关键字 break, continue, return 和 yield 转移程序控制

条件语句(Conditional statement)

if statement

C# 中的 if 语句的语法与 C, C++ 和 Java 相同:

if (condition)
{
    // Do something
}
else
{
    // Do something else
}

if 语句计算条件表达式决定是否执行 if 语句块(if-body),否则执行 else 语句块(else-body),else 语句块是可选的。else 语句块中可以使用层叠(common cascade)的 if, else if, else if, else if, ..., else 语句:

using System;

public class IfStatementSample
{
    public void IfMyNumberIs()
    {
        int myNumber = 5;

        if (myNumber == 4)
        {
            Console.WriteLine("This will not be shown because myNumber is not 4.");
        }
        else if (myNumber < 0)
        {
            Console.WriteLine("This will not be shown because myNumber is not negative.");
        }
        else if( myNumber % 2 == 0 )
        {
            Console.WriteLine("This will not be shown because myNumber is not even.");
        }
        else
        {
            Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");
        }
    }
}

switch statement

C# 中的 switch 语句的语法与 C, C++ 和 Java 相似:

switch (nCPU)
{
    case 0:
        Console.WriteLine("You don't have a CPU! :-)");
        break;
    case 1:
        Console.WriteLine("Single processor computer");
        break;
    case 2:
        Console.WriteLine("Dual processor computer");
        break;
        // Stacked cases
    case 3:
        // falls through
    case 4:
        // falls through
    case 5:
        // falls through
    case 6:
        // falls through
    case 7:
        // falls through
    case 8:
        Console.WriteLine("A multi processor computer");
        break;
    default:
        Console.WriteLine("A seriously parallel computer");
        break;
}

其中,default 语句是可选的。如果没有定义 default 语句,则会隐式添加一个空的 default 语句。

不同于 C,C# 中的 switch 与可以应用在字符串变量上,例如:

switch (aircraftIdent)
{
    case "C-FESO":
        Console.WriteLine("Rans S6S Coyote");
        break;
    case "C-GJIS":
        Console.WriteLine("Rans S12XL Airaile");
        break;
    default:
        Console.WriteLine("Unknown aircraft");
        break;
}

迭代语句(Iteration statement)

do ... while loop

do ... while 循环语法:
do body while (condition)

do ... while 循环始终会执行一次循环体,然后判断是否满足 while 中的条件,决定是否再次执行循环体。

using System;

public class DoWhileLoopSample
{
    public void PrintValuesFromZeroToTen
    {
        int number = 0;

        do
        {
            Console.WriteLine(number++.ToString());
        }
        while (number <= 10)
    }
}

for loop

for 循环语法:
for (initialization; condition; iteration) body

  • initialization : 声明和初始化索引变量(index variable
  • condition : 决定是否执行循环体的条件
  • iteration : 循环体之后执行的语句,通常用于索引变量的自增或自减
public class ForLoopSample
{
    public void ForFirst100NaturalNumbers()
    {
        for (int i = 0; i < 100; i++)
        {
            System.Console.WriteLine(i.ToString());
        }
    }
}

foreach loop

foreach 循环与 for 循环相似,不过它没有迭代索引,所以可以用于对集合元素的迭代,语法:
foreach (variable-declaration in enumerable-expression) body

  • enumerable-expression : 一种实现了 IEnumerable 的类型的表达式,因此可用于任何数组或集合中
  • variable-declaration : 一个变量,表示循环体执行过程中 enumerable-expression 的连续元素,当没有更多元素可赋值给该变量时,循环结束
public class ForEachSample
{
    public void DoSomethingForEachItem()
    {
        string[] itemsToWrite = {"Alpha", "Bravo", "Charlie"};

        foreach (string item in itemsToWrite)
        {
            System.Console.WriteLine(item);
        }
    }
}

while loop

while 循环语法:
while (condition) body

while 循环会先判断是否满足条件,若满足,才会执行循环体。

using System;

public class WhileLoopSample
{
    public void RunForAWhile()
    {
        TimeSpan durationToRun = new TimeSpan(0, 0, 30);
        DateTime start = DateTime.Now;

        while (DateTime.Now - start < durationToRun)
        {
            Console.WriteLine("not finished yet");
        }
        Console.WriteLine("finished");
    }
}

跳转语句(Jump statement)

break

break 语句用于从 switch 语句的一个分支中退出,也可用于在 for, foreach, while, do ... while 语句中退出整个循环(after the end of the loop)。

using System;

namespace JumpSample
{
    public class Entry
    {
        static void Main(string[] args)
        {
            int i;
 
            for (i = 0; i < 10; i++) // see the comparison, i < 10
            {
                if (i >= 3)
                {
                    break; 
                    // Not run over the code, and get out of loop.
                    // Note: The rest of code will not be executed,
                    //       & it leaves the loop instantly
                }
            }
            // Here check the value of i, it will be 3, not 10.
            Console.WriteLine("The value of OneExternCounter: {0}", i);
        }
    }
}

continue

continue 语句用于退出当前循环(before the end of a loop)。

using System;

namespace JumpSample
{
    public class Entry
    {
        static void Main(string[] args)
        {
            int OneExternCounter = 0;

            for (int i = 0; i < 10; i++)
            {
                if (i >= 5)
                {
                    continue;   // Not run over the code, and return to the beginning 
                                // of the scope as if it had completed the loop
                }
                OneExternCounter += 1;
            }
            // Here check the value of OneExternCounter, it will be 5, not 10.
            Console.WriteLine("The value of OneExternCounter: {0}", OneExternCounter);
        }
    }
}

return

return 关键字标识函数或方法的返回值,并使程序跳转到函数的结尾。

namespace JumpSample
{
    public class Entry
    {
        static int Fun()
        {
            int a = 3;
            return a; // the code terminates here from this function
            a = 9;    // here is a block that will not be executed
        }

        static void Main(string[] args)
        {
            int OnNumber = Fun();
            // the value of OnNumber is 3, not 9...
        }
    }
}

yield

yield 关键字用于定义用于为枚举器生成值的迭代器块(iterator block),通常用在实现 IEnumerable 接口的方法中,来实现一个迭代器。

using System;
using System.Collections;

public class YieldSample
{
    public static IEnumerable MyCounter(int stop, int step)
    {
        int i;

        for (i = 0; i < stop; i += step)
        {
            yield return i;
        }
    }

    static void Main()
    {
        foreach (int j in MyCounter(10, 2))
        {
            Console.WriteLine("{0} ", j);
        }
        // Will display 0 2 4 6 8
    }
}

throw

throw 关键字用于抛出异常。
如果它位于 try 语句块内,它将把控制转移到匹配这个异常的 catch 语句块,否则,它将检查当前调用环境下是否有任何包含匹配这个异常的 catch 语句块的函数(it will check if any calling functions are contained within the matching catch block),并将控制转移到那里。如果没有函数包含匹配这个异常的 catch 语句块,则程序可能会因为异常未被处理而终止。

namespace ExceptionSample
{
    public class Warrior
    {
        private string Name { get; set; }

        public Warrior(string name)
        {
            if (name == "Piccolo")
            {
                throw new Exception("Piccolo can't battle!");
            }
        }
    }

    public class Entry
    {
        static void Main(string[] args)
        {
            try
            {
                Warrior a = new Warrior("Goku");
                Warrior b = new Warrior("Vegeta");
                Warrior c = new Warrior("Piccolo"); // exception here!
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

标签:语句,Console,C#,控制流,笔记,else,while,WriteLine,public
From: https://www.cnblogs.com/snoopy1866/p/17520629.html

相关文章

  • 【C#/.NET】探究Task中ConfigureAwait方法
    ​ 目录 引言ConfigureAwait方法的作用和原理ConfigureAwait方法的使用场景非UI线程场景避免上下文切换避免死锁ConfigureAwait方法的注意事项在UI线程使用时需要小心嵌套搭配使用总结 引言        在.NET开发中,我们经常使用异步编程来提高应用程序的......
  • autosys document
    http://support.ca.com/phpdocs/0/common/impcd/r11/troubleshooting/doc/autsys_diag_tips_110607.pdf autsys_diag_tips_110607.pdf http://writetrends.files.wordpress.com/2009/09/autosys-edk2uaj45cie.pdfUnicenterAutoSysJobManagementTableofContentsIntrodu......
  • spring中的controller种类
     http://xiaohu0901.iteye.com/blog/608906一、springmvc中常见controller1、org.springframework.web.servlet.mvc.ParameterizableViewController  这个controller主要用在不需要后台业务逻辑处理的地方,直接在配置文件中指定视图渲染的路径,如下:  <beanid="paramCont......
  • ScheduledThreadPoolExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(bo
    MethodSummary voidexecute(Runnable          Executecommandwithzerorequireddelay. booleangetContinueExistingPeriodicTasksAfterShutdownPolicy()          Getthepolicyonwhethertocontinueexecutingexistingperiodictaskseven......
  • spring 监听器 IntrospectorCleanupListener简介
     spring中的提供了一个名为org.springframework.web.util.IntrospectorCleanupListener的监听器。它主要负责处理由JavaBeans Introspector的使用而引起的缓冲泄露。spring中对它的描述如下: 它是一个在web应用关闭的时候,清除JavaBeansIntrospector的监听器.在web.xml中......
  • Spring factory load
    if(!classpathPrefix.endsWith("/"))classpathPrefix=classpathPrefix+"/";GenericApplicationContextappContext=null;if(useCache)appContext=getCachedContext(classpathPrefix,batchName);if(appContext!=null){......
  • 在spring 的jdbc sql中使用in 语句
    1.<propertyname="sqlSelectPricesForHoldAssetByDate"><value>selectA.ASSETPRICEID,A.ASSETID,A.SOURCE,A.ASOFDATE,A.CURRENCY,A.BID,A.ASKfromassetpriceAINNERJOINloanfacilitylfONA.assetid=lf.assetidwh......
  • Excel函数大全
    Excel函数大全数据库和清单管理函数DAVERAGE返回选定数据库项的平均值DCOUNT计算数据库中包含数字的单元格的个数DCOUNTA计算数据库中非空单元格的个数DGET从数据库中提取满足指定条件的单个记录DMAX返回选定数据库项中的最大值DMIN返回选定数据......
  • Eclipse里web的依赖工程部署的简便方法
    用Eclipse开发项目,曾经为依赖工程的部署问题头疼过,用了MyEclipse之后就没有仔细去研究,最近研究了下,还真找到了比较简便的方法,之前都是采用Ant打jar包,copy到web工程,或者通过LinkSource,直接把依赖工程编译到web工程下边,但这样感觉总不是个长久之计,因为前者每次编译都要打包太过麻烦,......
  • 什么是JAVA内容仓库(Java Content Repository)
    内容仓库模型JSR-170是这样定义内容仓库的,内容仓库由一组workspace(工作空间)组成,这些workspace通常应该包含相似的内容。一个内容仓库有一个到多个workspace。每个workspace都是一个树状结构,都有一个唯一的树根节点(rootnode)。树上的item(元素)或者是个node(节点)或者是个property......