蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

CSHARPWindows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。ExploreDecision.cs
ExploreDecision.cs189 行
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())
        ));
    }
}
本例需在 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/csharp-decision-lab/ExploreDecision.cs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreDecision.cs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C#

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

下载课程关联工程包:C#

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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