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

C# 教程

概述 C# 语言定位、适用读者与前置基础、编译执行流程、首个 HelloWorldApplication 程序及官方学习资源,并在本地 .NET Framework 4.x Visual C# 编译器(csc.exe)实测验证。

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

学完这一章,你能够

C# 语言定位与学习前置条件

C# 是由微软(Microsoft)推出的现代、通用、面向对象的程序设计语言,语法结构清晰且兼顾工程表达力。本系列教程将从基础语法起步,循序渐进地展开类型系统、面向对象封装继承多态、委托事件、泛型与并发等进阶机制,并配合可离线运行的本地实验帮助读者动手实践。

本教程面向希望系统掌握 C# 的初学者,完成学习后可建立扎实的工程编程基础并过渡到中级开发水平。由于 C# 在语句风格、块结构与运算符设计上继承了 C 与 C++ 的传统,具备 C/C++ 基础的读者能够更快适应;即便从零起步,按章节循序练习亦可顺利掌握。

编译执行与第一个 Hello World 实例

编写 C# 程序后需经编译器编译并交由 .NET 运行时执行,既可在本地使用 `.NET SDK`(`dotnet run`)或 Windows 自带 `.NET Framework 4.x` 的 `csc.exe` 命令行工具编译运行,也可在在线 C# 沙箱中快速体验。最简入门示例在 `HelloWorldApplication` 命名空间内声明 `HelloWorld` 类,并在程序入口 `static void Main(string[] args)` 中调用 `Console.WriteLine("Hello World!");` 输出问候语(交互式控制台调试时常追加 `Console.ReadKey();` 防止窗口闪退)。本站已在本地 `csc.exe`(C# 5.0)编译运行 `ExploreTutorial.cs`,实测精确输出 `Hello World!` 且反射确认 `Main` 入口签名与 `System.Console` 命名空间归属。

C# 官方文档与常用学习资源

系统学习 C# 时可配合以下权威公开资料查证细节:Microsoft Learn 官方《C# Programming Guide》(详述语言特性与 .NET 基础类库用法)、Visual Studio 官方下载页面(Windows 旗舰集成开发环境)、Mono 项目官网(早期开源跨平台实现,现仍应用于部分游戏引擎等场景)以及维基百科 `C Sharp (programming language)` 词条(梳理语言演进历史与规范脉络)。

在本地 csc.exe (.NET Framework 4.x) 编译运行 HelloWorld 并校验 Main 入口签名

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

namespace HelloWorldApplication
{
    public class HelloWorld
    {
        public static string Run(TextWriter output)
        {
            /* 我的第一个 C# 程序 */
            output.WriteLine("Hello World!");
            return output.ToString().Trim();
        }
    }
}

public class ExploreTutorial
{
    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: Hello World output
        StringWriter sw = new StringWriter();
        string actualHello = HelloWorldApplication.HelloWorld.Run(sw);
        cases.Add(MakeCase(
            "hello_world_output",
            "运行 HelloWorldApplication.HelloWorld 输出标准问候语 Hello World!",
            JsonEscape("Hello World!"),
            JsonEscape(actualHello)
        ));

        // Case 2: Main entry signature inspection
        MethodInfo mainMethod = typeof(ExploreTutorial).GetMethod("Main", BindingFlags.Public | BindingFlags.Static);
        ParameterInfo[] mainParams = mainMethod != null ? mainMethod.GetParameters() : new ParameterInfo[0];
        bool mainOk = mainMethod != null
            && mainMethod.IsStatic
            && mainMethod.ReturnType == typeof(void)
            && mainParams.Length == 1
            && mainParams[0].ParameterType == typeof(string[]);
        string actualSig = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"static_void\":{0},\"param_type\":{1},\"clr_major\":{2}}}",
            mainOk ? "true" : "false",
            JsonEscape(mainParams.Length == 1 ? mainParams[0].ParameterType.FullName : ""),
            Environment.Version.Major
        );
        string expectedSig = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"static_void\":true,\"param_type\":{0},\"clr_major\":4}}",
            JsonEscape("System.String[]")
        );
        cases.Add(MakeCase(
            "main_entry_signature",
            "反射校验 static void Main(string[] args) 入口签名与 .NET Framework 4.x CLR 主版本号",
            expectedSig,
            actualSig
        ));

        // Case 3: System namespace and core BCL types
        string actualBcl = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"console_ns\":{0},\"string_type\":{1},\"hello_ns\":{2}}}",
            JsonEscape(typeof(Console).Namespace),
            JsonEscape(typeof(string).FullName),
            JsonEscape(typeof(HelloWorldApplication.HelloWorld).Namespace)
        );
        string expectedBcl = string.Format(
            CultureInfo.InvariantCulture,
            "{{\"console_ns\":{0},\"string_type\":{1},\"hello_ns\":{2}}}",
            JsonEscape("System"),
            JsonEscape("System.String"),
            JsonEscape("HelloWorldApplication")
        );
        cases.Add(MakeCase(
            "dotnet_ecosystem_basics",
            "校验 System.Console、System.String 与自定义命名空间 HelloWorldApplication 归属",
            expectedBcl,
            actualBcl
        ));

        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())
        ));
    }
}
预期结果 · 待实际运行核验
  • 确认 HelloWorldApplication.HelloWorld 输出 Hello World!,反射校验 static void Main(string[] args) 入口与 System.Console/System.String 归属。
在本地 csc.exe (.NET Framework 4.x) 编译运行 HelloWorld 并校验 Main 入口签名

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

当前源码 SHA256:53b1050b248da79d84b181f47dffe98d12faa722cb2a49a7caae03561450bb85

下载本站示例源码

本地运行

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

下载C# 教程实验

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

ZIP SHA256:708d760130632b28951d55b6af6c8fdc9aa6b3cc9cd1701fcb7dff4375c2d539

常见错误与边界

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

练习与解答

在控制台示例末尾添加 `Console.ReadKey();` 的主要目的是什么?在自动化离线测试脚本中为何通常省略它?

展开参考解答

在 IDE 中直接启动控制台程序时,`Console.ReadKey();` 会阻塞等待按键以防止输出窗口立刻关闭;而在自动化命令行或测试脚本中,标准输入并非交互终端,保留等待按键会导致进程挂起或抛出重定向异常。

规范与官方依据