蓝色天空.知识 · 实践 · 创造
我的收藏
Web Pages 教程目录 55章
Web Pages / LEARN BY DOING

Razor C# 逻辑

系统讲解 Razor C# 中的 @if 单分支、else 互斥分支、else if 多区间判断以及 @switch 多路分发与 C# 8+ switch 表达式演进,并纠正 case 冒号语法细节。

学完这一章,你能够

  • 系统讲解 Razor C# 中的 @if 单分支、else 互斥分支、else if 多区间判断以及 @switch 多路分发与 C# 8+ switch 表达式演进,并纠正 case 冒号语法细节。

If 单分支与 Else 互斥条件

编程逻辑的核心是依据运行时条件决定执行哪一段代码。C# 使用 `if` 语句对布尔表达式求值(返回 `true` 或 `false`):以 `@if` 开启条件代码块,判断条件写在圆括号 `(...)` 内,当条件为真时执行花括号 `{ ... }` 中的代码或 HTML 标记。例如当 `price = 50` 时,`@if (price > 30) { <p>The price is too high.</p> }` 会输出提示段落,而当 `price <= 30` 时不输出任何内容。

在 `if` 后追加 `else` 子句可以定义条件为假时的备用路径。当 `price = 20` 时,`price > 30` 为假,程序跳过 `if` 块并执行 `else` 块输出 `<p>The price is OK.</p>`;`else` 分支完整兜底除 `if` 条件以外的所有其他情况。

Else If 多条件链路与 Switch 分支

遇到多档区间或多项互斥条件时,可在 `if` 与 `else` 之间串联任意数量的 `else if` 分支。例如按 `price >= 30`、`else if (price > 20 && price < 30)` 与末尾无条件的 `else` 将价格划分为高、适中、低三档:系统自上而下依次求值,命中首个为真的分支即执行并跳过后续判断;若所有 `if` 与 `else if` 皆为假(例如 `price <= 20`),则由末尾 `else` 兜底处理。

针对同一离散值(如 `DateTime.Now.DayOfWeek.ToString()` 得到的星期名称 `day`)做等值匹配时,`@switch(day)` 比冗长的 `else if` 链条更清晰。待测试表达式写在 `switch(...)` 圆括号内;需特别注意语法细节:每个 `case` 标签以**冒号 `:`**(而非分号)结尾(例如 `case "Monday":`),其后可编写任意多条语句并以 `break;` 显式终止以防穿透;末尾的 `default:` 分支负责覆盖所有未匹配到的其他取值。在现代 C# 8+ / ASP.NET Core 中,还可以使用更简洁的 `switch` 表达式配合 `_` 弃元实现同样逻辑。

离线校验 Razor C# if/else/else if 区间边界与 switch 星期分发

含完整源码 · 125 行
展开查看收起
python
"""Offline ASP.NET Razor C# logic verification lab for Chapter 22 (razor-cs-logic)."""
import json

VERSION = "CPython 3.12.14 offline ASP.NET Razor C# logic semantic verifier (IIS/ASP.NET host absent)"


def case_cs_if_single_branch():
    def render_if(price):
        return "<p>The price is too high.</p>" if price > 30 else ""

    expected = {
        "price_50": "<p>The price is too high.</p>",
        "price_30": "",
        "price_20": "",
    }
    actual = {
        "price_50": render_if(50),
        "price_30": render_if(30),
        "price_20": render_if(20),
    }
    return {
        "name": "cs_if_single_branch",
        "summary": "验证 @if (price > 30) 单分支条件在大于、等于与小于阈值时的输出与空渲染行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cs_if_else_branch():
    def render_if_else(price):
        if price > 30:
            return "<p>The price is too high.</p>"
        return "<p>The price is OK.</p>"

    expected = {
        "price_20": "<p>The price is OK.</p>",
        "price_30": "<p>The price is OK.</p>",
        "price_45": "<p>The price is too high.</p>",
    }
    actual = {
        "price_20": render_if_else(20),
        "price_30": render_if_else(30),
        "price_45": render_if_else(45),
    }
    return {
        "name": "cs_if_else_branch",
        "summary": "验证 @if ... else 二选一互斥分支对 price=20/30/45 的精确落入结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cs_else_if_range_classification():
    def classify(price):
        if price >= 30:
            return "<p>The price is high.</p>"
        elif price > 20 and price < 30:
            return "<p>The price is OK.</p>"
        else:
            return "<p>The price is low.</p>"

    expected = {
        "price_30": "<p>The price is high.</p>",
        "price_25": "<p>The price is OK.</p>",
        "price_20": "<p>The price is low.</p>",
        "price_10": "<p>The price is low.</p>",
    }
    actual = {
        "price_30": classify(30),
        "price_25": classify(25),
        "price_20": classify(20),
        "price_10": classify(10),
    }
    return {
        "name": "cs_else_if_range_classification",
        "summary": "验证 @if / else if (price>20 && price<30) / else 多级区间划分与边界点 20/30 判定",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cs_switch_weekday_dispatch():
    def dispatch(day):
        if day == "Monday":
            msg = "This is the first weekday."
        elif day == "Thursday":
            msg = "Only one day before weekend."
        elif day == "Friday":
            msg = "Tomorrow is weekend!"
        else:
            msg = "Today is " + day
        return f"<p>{msg}</p>"

    expected = {
        "Monday": "<p>This is the first weekday.</p>",
        "Thursday": "<p>Only one day before weekend.</p>",
        "Friday": "<p>Tomorrow is weekend!</p>",
        "Wednesday": "<p>Today is Wednesday</p>",
    }
    actual = {d: dispatch(d) for d in ["Monday", "Thursday", "Friday", "Wednesday"]}
    return {
        "name": "cs_switch_weekday_dispatch",
        "summary": "验证 @switch(day) 精确匹配各 case 标签(冒号结尾 + break 终止)及 default 兜底分支",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_cs_if_single_branch(),
        case_cs_if_else_branch(),
        case_cs_else_if_range_classification(),
        case_cs_switch_weekday_dispatch(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
离线验证器确认 if 单分支、if-else、else if 边界值(20/25/30)以及 switch 各 case 冒号标签与 default 兜底分支全部准确命中。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a3037.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Web Pages

课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a3037.zip

下载课程关联工程包:Web Pages

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3049.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`case` 标签后必须使用冒号 `:`(不是分号 `;`);C# 禁止非空 `case` 分支隐式穿透到下一个 `case`,因此分支末尾必须用 `break;`、`return;` 或 `throw` 显式结束控制流。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习