ASP.NET Razor - condizioni logiche C#
Logica di programmazione: eseguire codice basato su condizioni.
If condizione
C# ti permette di eseguire codice basato su condizioni.
Per testare una condizione, puoi usare istruzione if.L'istruzione if restituirà true o false in base al tuo test:
- L'istruzione if avvia un blocco di codice
- La condizione si trova tra parentesi
- Se la condizione è vera, esegui il codice tra i parentesi graffati
实例
@{var prezzo=50;} <html> <body> @if (prezzo > 30) { <p>价格太高。</p> } </body> </html>
运行实例
Else condizione
Le istruzioni if possono includere else condizione.
else condizione definisce il codice eseguito quando la condizione è false.
实例
@{var prezzo=20;} <html> <body> @if (prezzo > 30) { <p>价格太高。</p> } else { <p>价格合适。</p> } </body> </html>
运行实例
Note:Nell'esempio sopra, se il prezzo non è maggiore o uguale a 30, esegui il resto delle istruzioni.
Else If condizione
può essere else if condizioneTesta più condizioni:
实例
@{var prezzo=25;} <html> <body> @if (prezzo >= 30) { <p>价格太高。</p> } else if (price>20 && price<30) { <p>价格合适。</p> } else { <p>价格合适。</p> } </body> </html>
运行实例
在上面的例子中,如果第一个条件为 true,则执行第一个代码块。
否则,如果下一个条件为 true,则执行第二个代码块。
您能够设置任意数量的 else if 条件。
如果 if 和 else if 条件均不为 true,则执行最后一个 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>
运行实例
测试值 (day) 位于括号中。每个具体的测试条件以 case 关键词开头,以冒号结尾,其后允许任意数量的代码行,以 break 语句结尾。如果测试值匹配 case 值,则执行代码行。
switch 代码块可为其余的情况设置默认的 case (default:),允许在所有 case 均不为 true 时执行代码。