ASP.NET Razor C# 邏輯
編程邏輯:根據條件執行代碼。
If 條件
C# 允許根據條件執行代碼。
使用if語句來判斷條件。 根據判斷結果,if 語句返回true 或者false:
- if 語句開始一個代碼塊
- 條件寫在括號裡
- 如果條件為真,大括號內的代碼被執行
實例
@{var
price=50;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
</body>
</html>
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
</body>
</html>
運行實例»
Else 條件
if語句可以包含else條件 。
else 條件定義了當條件為假時被執行的代碼。
實例
@{var
price=20;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
運行實例»
註釋:在上面的實例中,如果第一個條件為真,if塊的代碼將會被執行。 else 條件覆蓋了除if 條件之外的"其他所有情況"。
Else If 條件
多個條件判斷可以使用else if條件 :
實例
@{var
price=25;}
<html>
<body>
@if (price>=30)
{
<p>The price is high.</p>
}
else if (price>20 && price<30)
{
<p>The price is OK.</p>
}
else
{
<p>The price is low.</p>
}
</body>
</html>
<html>
<body>
@if (price>=30)
{
<p>The price is high.</p>
}
else if (price>20 && price<30)
{
<p>The price is OK.</p>
}
else
{
<p>The price is low.</p>
}
</body>
</html>
運行實例»
在上面的實例中,如果第一個條件為真,if 塊的代碼將會被執行。
如果第一個條件不為真且第二個條件為真,else if 塊的代碼將會被執行。
else if 條件的數量不受限制。
如果if 和else if 條件都不為真,最後的else 塊(不帶條件)覆蓋了"其他所有情況"。
Switch 條件
switch塊可以用來測試一些單獨的條件:
實例
@{
var weekday=DateTime.Now.DayOfWeek;
var day=weekday.ToString();
var message="";
}
<html>
<body>
@switch(day)
{
case "Monday":
message="This is the first weekday.";
break;
case "Thursday":
message="Only one day before weekend.";
break;
case "Friday":
message="Tomorrow is weekend!";
break;
default:
message="Today is " + day;
break;
}
<p> @message </p>
</body>
</html>
var weekday=DateTime.Now.DayOfWeek;
var day=weekday.ToString();
var message="";
}
<html>
<body>
@switch(day)
{
case "Monday":
message="This is the first weekday.";
break;
case "Thursday":
message="Only one day before weekend.";
break;
case "Friday":
message="Tomorrow is weekend!";
break;
default:
message="Today is " + day;
break;
}
<p> @message </p>
</body>
</html>
運行實例»
測試值(day)是寫在括號中。 每個單獨的測試條件都有一個以分號結束的case 值和以break 語句結束的任意數量的代碼行。 如果測試值與case 值相匹配,相應的代碼行被執行。
switch 塊有一個默認的情況(default:),當所有的指定的情況都不匹配時,它覆蓋了"其他所有情況"。