VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 网站开发 > ASP.net 4.0教程 >
  • asp.net教程之Razor - C# 逻辑条件

编程逻辑:根据条件执行代码。

If 条件

C# 允许根据条件执行代码。

使用 if 语句来判断条件。根据判断结果,if 语句返回 true 或者 false:

  • if 语句开始一个代码块
  • 条件写在括号里
  • 如果条件为真,大括号内的代码被执行

实例


  1. @{var price=50;} <html> <body> @if (price>30) { <p>The price is too high.</p> } </body> </html>
复制

Else 条件

if 语句可以包含 else 条件

else 条件定义了当条件为假时被执行的代码。

实例


  1. @{var price=20;} <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 条件

实例


  1. @{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>
复制

在上面的实例中,如果第一个条件为真,if 块的代码将会被执行。

如果第一个条件不为真且第二个条件为真,else if 块的代码将会被执行。

else if 条件的数量不受限制。

如果 if 和 else if 条件都不为真,最后的 else 块(不带条件)覆盖了"其他所有情况"。

Switch 条件

switch 块可以用来测试一些单独的条件:

实例


  1. @{ 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:),当所有的指定的情况都不匹配时,它覆盖了"其他所有情况"。


相关教程