今天学习了C#的分支和循环。
分支有3种技术:三元运算符,if 语句,switch 语句。
1.三元运算符语法:
<test>?<resultTrue>:<resultFalse>
其中,计算<test>可以得到一个布尔值。看一个范例:
string resultString=(myInteger<10)?"Less than 10":"Greater than or equal to 10";
如果myInteger的值小于10,就把第一个字符串赋给resultString;如果myInteger的值大于或等于10,就把第二个
字符串赋给resultString.
2.if语句
语法如下:
if(<test>)
<code executed if(test is true)>;
<code executed if(test is true)>;
先执行<test>(其计算结果必须是一个布尔值),如果<test>的结果是true,就执行该语句下面的代码。
也可以将else 语句和 if 语句合并使用:
if(<test>)
{
<code executed if<test>is true>;
}
else
{
<code executed if<test>is false>;
}
{
<code executed if<test>is true>;
}
else
{
<code executed if<test>is false>;
}
3. switch语句
基本语法:
1switch(<testVar>)
2{
3 case<comparisonVar1>:
4 <code to execute if<testVar>==<comparisonVar1>>
5break;
6 case<comparisonVar2>:
7 <code to execute if<testVar>==<comparisonVar2>>
8break;
9
10 case<comparisonVarN>:
11 <code to execute if<testVar>==<comparison VarN>>
12break;
13 default:
14 <code to execute if<testVar>!=comparison Vars>
15break;
16}
2{
3 case<comparisonVar1>:
4 <code to execute if<testVar>==<comparisonVar1>>
5break;
6 case<comparisonVar2>:
7 <code to execute if<testVar>==<comparisonVar2>>
8break;
9
10 case<comparisonVarN>:
11 <code to execute if<testVar>==<comparison VarN>>
12break;
13 default:
14 <code to execute if<testVar>!=comparison Vars>
15break;
16}