C# 流程控制分支 if 語(yǔ)句
if語(yǔ)句的功能比較多,是一種有效的決策方式。與?:語(yǔ)句不同的是,if語(yǔ)句沒(méi)有結(jié)果(所以不在賦值語(yǔ)句中 使用它),使用該語(yǔ)句是為了根據(jù)條件執(zhí)行其他語(yǔ)句。 if語(yǔ)句最簡(jiǎn)單的語(yǔ)法如下:
if (<test>)
<code executed if <test> is true>;
先執(zhí)行<tesl>(其計(jì)算結(jié)果必須是一個(gè)布爾值,這樣代碼才能編譯),如果<test>的計(jì)算結(jié)果是true,就執(zhí)行該語(yǔ) 句之后的代碼。這段代碼執(zhí)行完畢后,或者因?yàn)?lt;test>的計(jì)算結(jié)果是&lse,而沒(méi)有執(zhí)行這段代碼,將繼續(xù)執(zhí)行 后面的代碼行。
也可將else語(yǔ)句和if語(yǔ)句合并使用,指定其他代碼。如果<test>的計(jì)算結(jié)果是false,就執(zhí)行else語(yǔ)句:
if {<test>)
<code executed if <test> is true>;
else
<code executed if <test> is false>;
可使用成對(duì)的花括號(hào)將這兩段代碼放在多個(gè)代碼行上:
if (<test>)
{
<code executed if <test> is true>;
}
else
{
<code executed if <test> is f3lse>;
}
例如,重新編寫上一節(jié)使用三元運(yùn)算符的代碼:
string resultstring = (mylnteger < 10) ? "Less than 10"
:"Greater than or equal to 10";
因?yàn)閕f語(yǔ)句的結(jié)果不能賦給一個(gè)變_1:,所以要單獨(dú)給變量賦值:
string resultstring;
if (mylnteger < 10)
resultstring = "Less than 10”7
else
resultstring = "Greater than or equal to 10";
這樣的代碼盡管比較冗長(zhǎng),但與對(duì)應(yīng)的三元運(yùn)算符形式相比,更便于閱讀和理解,也更靈活。
點(diǎn)擊加載更多評(píng)論>>