分支上控制下一步要执行哪些代码的过程.要跳转的代码行由某个条件语句来控制.这个条件语句用布尔逻辑,对测试值和一个或多个可能的的值进行比较.以下是3种分支技术:
三元运算符
if语句
switch语句
三元运算符
<test>?<resultIfTrue>:<resultIfFalse> 示例
string resultString=(myInteger<10)?"Less than 10" : "Greater than or equal to 10";
if语句
if语句没有结果(所以不在赋值语句中使用它)
if (<test>)
<code executed if <test> is true>;
else
<code executed if <test> is false>
示例1
//因为if语句的结果不能赋给一个变量,所以要单独反值赋给变量
string resultString;
if(myInteger<10)
resultString="Less than 10";
else
tesultString="Greater than or equal to 10";
与三元运算符相比,很容易阅读和理解,灵活性比较大
示例2
string comparison;
Console.WriteLine("Enter a number:");
double var1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter another number:");
double var2 = Convert.ToDouble(Console.ReadLine());
if (var1 < var2)
comparison = "less than";
else
{
if (var1 == var2)
comparison = "equal to";
else
comparison = "greater than";
}
Console.WriteLine("The first number is {0} the second number.", comparison);
Console.ReadKey();
也可以写成
if(var1<var2)
comparison="less than";
if(var1==var2)
comparison="equal to";
if(var1>var2)
comparison="greater than"; //缺点是无论var1和var2的值是什么,都要执行3个比较操作
使用if语句判断更多的条件
if (var1 == 1)
{
//do something
}
else
{
if (var1 == 2)
{
//do something else
}
else
{
if (var1 == 3 || var1 == 4)
{
//do something else
}
else
{
//do something else
}
}
} 也可以写成else if 语句结构
if (var1 == 1)
{
//do something
}
else if (var1 == 2)
{
//do something else
}
else if (var1 == 3 || var1 == 4)
{
//do something else
}
else
{
//do something else
} //这些else if语句实际上是两个独立的语句,它们的功能与上述代码相同,这样的代码更易于阅读.像这样的多个比较的操作应考虑另一分支结构:switch语句.
switch语句:
类似于if语句,它也是根据测试的值来有条件地执行代码,但是switch可以一次将测试变量与多个值进行比较,而不是公测试一个条件,这种测试公限于离散的值,而不是像"大于X"这样的子句.
示例1
const string myName = "karli";
const string sexyName = "angelina";
const string sillyName = "ploppy";
string name;
Console.WriteLine("What is your name?");
name = Console.ReadLine();
switch (name.ToLower())
{
case myName: //这里是冒号
Console.WriteLine("You have the same name as me!");
break;
case sexyName:
Console.WriteLine("My,what a sexy name you have!");
break;
case sillyName:
Console.WriteLine("That's a very silly name.");
break;
}
Console.WriteLine("hello {0}!",name);
Console.ReadKey();
name.ToLower()的值与每个case衙面的值进行比较,如果一个匹配,就执行为该匹配提供的语句,如果没有匹配就执行default部分中的代码,这里的break不能少,将中断switch语句的执行,而执行该结构衙面的语句.在执行完一个case衙再执行第二个case语句是非法的.也可用return语句,中断当前函数的运行.
每个case衙面都应该是常量,可提供字面值,如 case 1: case 2:
常量定义(用const声明)
const int intTwo=2;
不能分开,下面是错误的
const int intTwo;
intTwo=2;