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

实测 while/for/foreach/do...while、嵌套循环、break/continue 及带守卫的 for(;;) 循环

CSHARPWindows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。ExploreLoops.cs
ExploreLoops.cs169 行
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;

public class ExploreLoops
{
    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"
        );
    }

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

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

        // Case 1: while, for, foreach, do...while
        int wCount = 0, wSum = 0;
        while (wCount < 4)
        {
            wSum += wCount;
            wCount++;
        }
        int forSum = 0;
        for (int i = 1; i <= 5; i++)
        {
            forSum += i;
        }
        int[] nums = new int[] { 2, 4, 6, 8 };
        int foreachSum = 0;
        foreach (int n in nums)
        {
            foreachSum += n;
        }
        int doRuns = 0;
        do
        {
            doRuns++;
        } while (false); // 即使初始条件为假也至少执行一次
        string actualLoops = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"while_sum\":{0},\"for_sum\":{1},\"foreach_sum\":{2},\"do_while_false_runs\":{3}}}",
            wSum, forSum, foreachSum, doRuns
        );
        string expectedLoops = "{\"while_sum\":6,\"for_sum\":15,\"foreach_sum\":20,\"do_while_false_runs\":1}";
        cases.Add(MakeCase(
            "while_for_foreach_dowhile",
            "实测 while 前测循环、for/foreach 迭代以及 do...while 后测至少执行一次特性",
            expectedLoops,
            actualLoops
        ));

        // Case 2: Nested loops
        List<string> grid = new List<string>();
        for (int r = 1; r <= 3; r++)
        {
            for (int c = 1; c <= 3; c++)
            {
                grid.Add((r * c).ToString(CultureInfo.InvariantCulture));
            }
        }
        string actualNested = JsonEscape(string.Join(",", grid.ToArray()));
        string expectedNested = JsonEscape("1,2,3,2,4,6,3,6,9");
        cases.Add(MakeCase(
            "nested_loops_multiplication",
            "实测双层嵌套 for 循环生成 3x3 乘积序列",
            expectedNested,
            actualNested
        ));

        // Case 3: break and continue control statements
        List<string> oddBeforeBreak = new List<string>();
        for (int i = 1; i <= 10; i++)
        {
            if (i % 2 == 0)
            {
                continue; // 跳过偶数
            }
            if (i > 7)
            {
                break; // 超过 7 时终止循环
            }
            oddBeforeBreak.Add(i.ToString(CultureInfo.InvariantCulture));
        }
        string actualCtrl = JsonEscape(string.Join(",", oddBeforeBreak.ToArray()));
        string expectedCtrl = JsonEscape("1,3,5,7");
        cases.Add(MakeCase(
            "break_and_continue_control",
            "实测 continue 跳过偶数轮次与 break 提前终止循环的控制流效果",
            expectedCtrl,
            actualCtrl
        ));

        // Case 4: Infinite for(;;) loop bounded deterministically with break guard
        List<string> trapped = new List<string>();
        for (; ; )
        {
            trapped.Add("Hey! I am Trapped");
            if (trapped.Count >= 3)
            {
                break;
            }
        }
        string actualInf = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"iterations\":{0},\"sample\":{1}}}",
            trapped.Count,
            JsonEscape(trapped[0])
        );
        string expectedInf = "{\"iterations\":3,\"sample\":\"Hey! I am Trapped\"}";
        cases.Add(MakeCase(
            "infinite_for_loop_with_break_guard",
            "实测省略全部表达式的 for(;;) 无限循环结构并由显式 break 守卫安全退出",
            expectedInf,
            actualInf
        ));

        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-loops-lab/ExploreLoops.cs

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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