蓝色天空网mbsky.com · 知识 · 实践 · 创造C# · 本地阅读预览
教程 / 后端开发 / C#

C# 判断

系统梳理 C# 判断控制结构(if、if...else、嵌套 if、switch、嵌套 switch)、C# 6.0 Null 条件运算符 ?. 概念及三元条件运算符 ? : 的求值规则与实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

判断控制结构与分支语句家族

判断结构用于根据一个或多个布尔条件的真假决定程序的执行路径:条件为真时执行必需分支,条件为假时可执行可选替代分支。C# 提供了完整的分支工具集,涵盖 `if`、`if...else`、嵌套 `if`、`switch`、嵌套 `switch` 以及自 C# 6.0 引入用于安全成员访问的 Null 条件运算符 `?.`(详见下方判断语句参考表)。本站 `ExploreDecision.cs` 已对成绩分级 `if/else if/else` 嵌套分支以及双层 `switch` 路由分派进行了本地实测。

三元条件运算符 ? : 与单分支求值

条件运算符 `? :`(一般形式为 `Exp1 ? Exp2 : Exp3;`)可以简洁替代返回单值的 `if...else` 结构。求值时首先计算布尔条件 `Exp1`:若为 `true` 则仅计算 `Exp2` 并作为整个表达式的值;若为 `false` 则仅计算 `Exp3` 作为结果,未命中的分支不会被求值(注意问号与冒号的位置搭配)。此外针对 C# 6.0+ 的 `?.` 空条件访问,本机 C# 5.0 实验室以等价的显式判空保护 `(obj != null) ? obj.Name : null` 验证了非空取值与空引用安全返回 `null` 的一致语义。

C# 判断语句与空条件运算符参考表

语句 / 运算符功能说明
`if` 语句由一个布尔表达式后跟一条语句或语句块组成,条件为真时执行。
`if...else` 语句在 `if` 后附加可选 `else` 分支,布尔条件为假时执行 `else` 块。
嵌套 `if` 语句在 `if` 或 `else if` 分支内部继续嵌套 `if` / `else if` 处理多维条件。
`switch` 语句根据单个表达式匹配多个常量 `case` 分支(C# 禁止非空 case 隐式穿透,须以 `break`/`return` 结束)。
嵌套 `switch` 语句在外层 `switch` 的某个 `case` 分支内再嵌套一层 `switch` 进行二级分派。
Null 条件运算符 `?.`(C# 6.0+)在左侧对象非空时访问其属性或方法,为 `null` 时短路返回 `null`,避免冗长的层层判空 `if`。

实测 if/else 嵌套分级、双层 switch 路由、三元 ?: 单分支求值与等价空值保护

csharp · 阅读源码
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;

public class ExploreDecision
{
    private class UserProfile
    {
        public string Name;
    }

    private static string JsonEscape(string s)
    {
        if (s == null) return "null";
        StringBuilder sb = new StringBuilder();
        sb.Append('"');
        for (int i = 0; i < s.Length; i++)
        {
            char c = s[i];
            switch (c)
            {
                case '"': sb.Append("\\\""); break;
                case '\\': sb.Append("\\\\"); break;
                case '\b': sb.Append("\\b"); break;
                case '\f': sb.Append("\\f"); break;
                case '\n': sb.Append("\\n"); break;
                case '\r': sb.Append("\\r"); break;
                case '\t': sb.Append("\\t"); break;
                default:
                    if (c < 0x20)
                        sb.Append(string.Format(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)c));
                    else
                        sb.Append(c);
                    break;
            }
        }
        sb.Append('"');
        return sb.ToString();
    }

    private static string MakeCase(string name, string summary, string expectedJson, string actualJson)
    {
        bool passed = string.Equals(expectedJson, actualJson, StringComparison.Ordinal);
        return string.Format(
            CultureInfo.InvariantCulture,
            "{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
            JsonEscape(name),
            JsonEscape(summary),
            expectedJson,
            actualJson,
            passed ? "true" : "false"
        );
    }

    private static string ClassifyScore(int score, bool bonus)
    {
        if (score >= 90)
        {
            if (bonus)
            {
                return "A+";
            }
            else
            {
                return "A";
            }
        }
        else if (score >= 60)
        {
            return "Pass";
        }
        else
        {
            return "Fail";
        }
    }

    private static string RouteAction(int category, char code)
    {
        switch (category)
        {
            case 1:
                switch (code)
                {
                    case 'R': return "cat1-read";
                    case 'W': return "cat1-write";
                    default: return "cat1-other";
                }
            case 2:
                return "cat2-default";
            default:
                return "unknown";
        }
    }

    public static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.UTF8;
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

        List<string> cases = new List<string>();

        // Case 1: if, if...else, else if, nested if
        string actualIf = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"s95_bonus\":{0},\"s92_plain\":{1},\"s75\":{2},\"s40\":{3}}}",
            JsonEscape(ClassifyScore(95, true)),
            JsonEscape(ClassifyScore(92, false)),
            JsonEscape(ClassifyScore(75, false)),
            JsonEscape(ClassifyScore(40, false))
        );
        string expectedIf = "{\"s95_bonus\":\"A+\",\"s92_plain\":\"A\",\"s75\":\"Pass\",\"s40\":\"Fail\"}";
        cases.Add(MakeCase(
            "if_else_and_nested_if",
            "实测 if、if...else、else if 阶梯与嵌套 if 条件分支分流",
            expectedIf,
            actualIf
        ));

        // Case 2: switch and nested switch
        string actualSwitch = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"c1_R\":{0},\"c1_X\":{1},\"c2\":{2},\"c9\":{3}}}",
            JsonEscape(RouteAction(1, 'R')),
            JsonEscape(RouteAction(1, 'X')),
            JsonEscape(RouteAction(2, 'R')),
            JsonEscape(RouteAction(9, 'R'))
        );
        string expectedSwitch = "{\"c1_R\":\"cat1-read\",\"c1_X\":\"cat1-other\",\"c2\":\"cat2-default\",\"c9\":\"unknown\"}";
        cases.Add(MakeCase(
            "switch_and_nested_switch",
            "实测 switch 多值分支、default 兜底及嵌套 switch 分派",
            expectedSwitch,
            actualSwitch
        ));

        // Case 3: Ternary ? : operator and single-branch evaluation
        int branchCalls = 0;
        Func<string> trueBranch = delegate() { branchCalls += 1; return "yes"; };
        Func<string> falseBranch = delegate() { branchCalls += 10; return "no"; };
        string t1 = (10 > 3) ? trueBranch() : falseBranch();
        string t2 = (10 < 3) ? trueBranch() : falseBranch();
        string actualTernary = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"t1\":{0},\"t2\":{1},\"branch_calls_mask\":{2}}}",
            JsonEscape(t1),
            JsonEscape(t2),
            branchCalls
        );
        string expectedTernary = "{\"t1\":\"yes\",\"t2\":\"no\",\"branch_calls_mask\":11}";
        cases.Add(MakeCase(
            "ternary_conditional_operator",
            "实测 Exp1 ? Exp2 : Exp3 真假分支返回值且仅对命中分支求值",
            expectedTernary,
            actualTernary
        ));

        // Case 4: C# 5 null-guard equivalent to C# 6 null-conditional (?.)
        UserProfile existing = new UserProfile();
        existing.Name = "Alice";
        UserProfile missing = null;
        string name1 = (existing != null) ? existing.Name : null;
        string name2 = (missing != null) ? missing.Name : null;
        string actualNull = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"existing\":{0},\"missing_is_null\":{1}}}",
            JsonEscape(name1),
            (name2 == null) ? "true" : "false"
        );
        string expectedNull = "{\"existing\":\"Alice\",\"missing_is_null\":true}";
        cases.Add(MakeCase(
            "null_guard_equivalent_for_null_conditional",
            "以 C# 5 显式空值保护实测与 C# 6.0 ?. 运算符等价的安全成员访问语义",
            expectedNull,
            actualNull
        ));

        string version = ".NET Framework " + Environment.Version.ToString() + " (csc.exe C# 5.0)";
        Console.WriteLine(string.Format(
            CultureInfo.InvariantCulture,
            "{{\"version\":{0},\"cases\":[{1}]}}",
            JsonEscape(version),
            string.Join(",", cases.ToArray())
        ));
    }
}
预期结果 · 待实际运行核验
  • 确认四档成绩分级准确、双层 switch 分派命中预期分支、三元运算符每次仅求值命中分支且空引用保护返回 null。
实测 if/else 嵌套分级、双层 switch 路由、三元 ?: 单分支求值与等价空值保护

所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。

当前源码 SHA256:9a3fc8da71b1f5576e7243300ef6b00fa1436974e2797219bd4d8f4d2320e4d3

下载本站示例源码

本地运行

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

下载C# 判断实验

所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。

ZIP SHA256:8f43a261912b2efd02c1d4a3aeddeedf4dc2e1034e39550a896a184ba0e88673

常见错误与边界

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

练习与解答

在表达式 `cond ? FuncA() : FuncB()` 中,当 `cond` 为 `true` 时,`FuncB()` 会被调用吗?

展开参考解答

不会。条件运算符 `? :` 严格采用惰性单分支求值:仅当 `cond` 为 `true` 时求值 `FuncA()`,为 `false` 时才求值 `FuncB()`,未选中的分支完全不执行。

规范与官方依据