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

实测 Rectangle 面向对象语法、@if 标识符、上下文关键字与顶级语句等价逻辑

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

namespace RectangleApplication
{
    public class Rectangle
    {
        // 成员变量
        double length;
        double width;

        public void AcceptDetails()
        {
            length = 4.5;
            width = 3.5;
        }

        public double GetArea()
        {
            return length * width;
        }

        public string Display()
        {
            return string.Format(
                CultureInfo.InvariantCulture,
                "Length: {0}\nWidth: {1}\nArea: {2}",
                length,
                width,
                GetArea()
            );
        }
    }
}

public class ExploreBasicSyntax
{
    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 int Add(int a, int b)
    {
        return a + b;
    }

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

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

        // Case 1: Rectangle class, fields, methods, instantiation
        RectangleApplication.Rectangle r = new RectangleApplication.Rectangle();
        r.AcceptDetails();
        string actualRect = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"area\":{0},\"display\":{1}}}",
            r.GetArea().ToString("0.00", CultureInfo.InvariantCulture),
            JsonEscape(r.Display())
        );
        string expectedRect = "{\"area\":15.75,\"display\":\"Length: 4.5\\nWidth: 3.5\\nArea: 15.75\"}";
        cases.Add(MakeCase(
            "rectangle_class_and_members",
            "实例化 Rectangle 类并验证成员变量 length/width、GetArea 面积计算与 Display 输出",
            expectedRect,
            actualRect
        ));

        // Case 2: Comments and using directive
        /* 多行注释示例:
           编译器会忽略此区块内的所有文本 */
        int value = 7; // 单行注释示例
        bool systemImported = typeof(Console).Namespace == "System";
        string actualComment = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"value\":{0},\"system_imported\":{1}}}",
            value,
            systemImported ? "true" : "false"
        );
        string expectedComment = "{\"value\":7,\"system_imported\":true}";
        cases.Add(MakeCase(
            "comments_and_using_directive",
            "验证 using System 引入命名空间以及单行/多行注释对程序执行无副作用",
            expectedComment,
            actualComment
        ));

        // Case 3: Verbatim @keyword identifier, case sensitivity, contextual keywords as identifiers
        int @if = 100;
        int area = 10;
        int Area = 20;
        string get = "contextual_get";
        string set = "contextual_set";
        int reservedCount = 79; // 含表格列出的 in/out 泛型修饰条目共 79 项(77 个独立保留字)
        int contextualCount = 18; // 表格列出的 18 项上下文关键字条目
        string actualIdent = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"at_if\":{0},\"case_diff\":{1},\"contextual_vars\":{2},\"reserved_entries\":{3},\"contextual_entries\":{4}}}",
            @if,
            (area != Area) ? "true" : "false",
            JsonEscape(get + "+" + set),
            reservedCount,
            contextualCount
        );
        string expectedIdent = "{\"at_if\":100,\"case_diff\":true,\"contextual_vars\":\"contextual_get+contextual_set\",\"reserved_entries\":79,\"contextual_entries\":18}";
        cases.Add(MakeCase(
            "keywords_and_identifiers",
            "实测 @if 关键字转义标识符、大小写区分、上下文关键字在普通作用域作变量名与表格条目数",
            expectedIdent,
            actualIdent
        ));

        // Case 4: Top-level statements equivalent logic in C# 5 Main
        int number = 42;
        string message = "The answer to life, the universe, and everything is";
        string formatted = string.Format(CultureInfo.InvariantCulture, "{0} {1}.", message, number);
        int sum = Add(1, 2);
        int[] numbers = new int[] { 1, 2, 3, 4, 5 };
        int[] evens = numbers.Where(n => n % 2 == 0).ToArray();
        string evenText = string.Join(", ", evens.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray());
        bool caughtDivZero = false;
        try
        {
            int zero = 0;
            int unused = number / zero;
            if (unused == 0) caughtDivZero = false;
        }
        catch (DivideByZeroException)
        {
            caughtDivZero = true;
        }
        string actualTop = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"formatted\":{0},\"add_1_2\":{1},\"evens\":{2},\"caught_div_zero\":{3}}}",
            JsonEscape(formatted),
            sum,
            JsonEscape(evenText),
            caughtDivZero ? "true" : "false"
        );
        string expectedTop = "{\"formatted\":\"The answer to life, the universe, and everything is 42.\",\"add_1_2\":3,\"evens\":\"2, 4\",\"caught_div_zero\":true}";
        cases.Add(MakeCase(
            "top_level_equivalent_logic",
            "在 C# 5 Main 方法中实测与顶级语句示例等价的变量格式化、Add 方法、LINQ 偶数过滤与除零异常捕获",
            expectedTop,
            actualTop
        ));

        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-basic-syntax-lab/ExploreBasicSyntax.cs

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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