C# 程序结构
逐行拆解最小 C# Hello World 程序的命名空间、类、方法、Main 入口、注释与语句规范,并对比 Visual Studio IDE 与 csc 命令行两种编译执行流程。
学完这一章,你能够
- 逐行拆解最小 C# Hello World 程序的命名空间、类、方法、Main 入口、注释与语句规范,并对比 Visual Studio IDE 与 csc 命令行两种编译执行流程。
最小 C# 程序的组成构件与示例
深入语言细节前,先认识一个最小可运行 C# 程序的骨架。典型的 C# 程序由七类要素组成:命名空间声明(`namespace`)、类(`class`)、类方法、类属性、作为执行起点的 `Main` 方法、语句与表达式以及注释。C# 源代码文件使用 `.cs` 后缀;在 `test.cs` 中定义 `namespace HelloWorldApplication` 与 `class HelloWorld`,并在 `static void Main(string[] args)` 内调用 `Console.WriteLine("Hello World");` 和 `Console.ReadKey();`,编译运行后控制台将输出 `Hello World`。
逐行剖析该程序结构:1)首行 `using System;` 用于引入 `System` 命名空间(实际程序常含多条 `using`);2)`namespace HelloWorldApplication` 将相关类组织在统一命名空间中以避免命名冲突;3)`class HelloWorld` 封装数据与行为方法(此处仅定义入口方法 `Main`);4)`Main` 方法是整个 C# 程序的唯一入口点,决定启动后的执行动作;5)`/* ... */` 属于注释,编译阶段会被完全忽略;6)`Console.WriteLine("Hello World");` 调用 `System.Console` 类的静态 `WriteLine` 方法向屏幕输出一行文本;7)末尾 `Console.ReadKey();` 用于在 Visual Studio 启动控制台调试时暂停等待按键,避免窗口执行完毕瞬间关闭。
书写 C# 代码还需牢记四项基本规则:C# 严格区分大小写(`count` 与 `Count` 互不干扰);所有语句与表达式必须以英文分号 `;` 结尾;程序总是从 `Main` 方法开始执行;与 Java 要求公开类名与文件名严格一致不同,C# 源文件名可以与其中声明的类名不同(例如 `ExploreProgramStructure.cs` 内可直接声明 `HelloWorld` 类)。本站实测已同时验证上述命名空间、大小写隔离、注释忽略与文件名独立性。
通过 Visual Studio 与 csc 命令行编译执行
若使用 Visual Studio 编译运行 C# 控制台程序,常规流程为:启动 Visual Studio → 菜单栏选择 `File -> New -> Project` → 在模板中选取 Visual C# / Windows → 选择 Console Application → 指定项目名称并点击 OK → 在解决方案资源管理器(Solution Explorer)中打开自动生成的代码文件并编辑代码 → 点击运行按钮或按 `F5` 启动调试,控制台窗口随即输出 `Hello World`。
若偏好轻量命令行编译(基于 .NET Framework 的 `csc.exe`):先用任意文本编辑器写好代码并保存为 `helloworld.cs`;打开命令提示符切换到该文件所在目录;输入 `csc helloworld.cs` 回车编译,无语法错误时会在当前目录生成可执行文件 `helloworld.exe`;接着输入 `helloworld` 回车运行,屏幕即可打印 `Hello World`。本站本地验证正是直接调用系统 `csc.exe` 完成编译并反射确认程序集入口点为 `Main`。
实测 C# 命名空间/类结构、文件名与类名独立性、大小写敏感及 Main 入口反射
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 string Greeting { get; set; }
public HelloWorld()
{
Greeting = "Hello World";
}
public string PrintGreeting(TextWriter writer)
{
/* 我的第一个 C# 程序 */
writer.WriteLine(Greeting);
return writer.ToString().Trim();
}
}
}
public class ExploreProgramStructure
{
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: Namespace, class, property, method, and filename independence
HelloWorldApplication.HelloWorld hw = new HelloWorldApplication.HelloWorld();
StringWriter sw = new StringWriter();
string output = hw.PrintGreeting(sw);
bool filenameDiffersFromClass = !string.Equals("ExploreProgramStructure", typeof(HelloWorldApplication.HelloWorld).Name, StringComparison.Ordinal);
string actualStruct = string.Format(
CultureInfo.InvariantCulture,
"{{\"output\":{0},\"namespace\":{1},\"class_name\":{2},\"filename_independent\":{3}}}",
JsonEscape(output),
JsonEscape(typeof(HelloWorldApplication.HelloWorld).Namespace),
JsonEscape(typeof(HelloWorldApplication.HelloWorld).Name),
filenameDiffersFromClass ? "true" : "false"
);
string expectedStruct = "{\"output\":\"Hello World\",\"namespace\":\"HelloWorldApplication\",\"class_name\":\"HelloWorld\",\"filename_independent\":true}";
cases.Add(MakeCase(
"hello_world_namespace_and_class",
"验证 HelloWorldApplication 命名空间、HelloWorld 类输出 Hello World 且允许文件名与类名不同",
expectedStruct,
actualStruct
));
// Case 2: Case sensitivity and comments ignored by compiler
int count = 10;
int Count = 25;
/* count = 999; 块注释内的语句不会被编译执行 */
// Count = 888; 单行注释同样被编译器忽略
string actualCase = string.Format(
CultureInfo.InvariantCulture,
"{{\"lower\":{0},\"upper\":{1},\"sum\":{2}}}",
count,
Count,
count + Count
);
string expectedCase = "{\"lower\":10,\"upper\":25,\"sum\":35}";
cases.Add(MakeCase(
"case_sensitivity_and_comments",
"实测 C# 标识符大小写敏感(count 与 Count 独立)且单行/多行注释被编译器忽略",
expectedCase,
actualCase
));
// Case 3: Main entry point and System.Console.WriteLine metadata
MethodInfo entry = Assembly.GetExecutingAssembly().EntryPoint;
MethodInfo writeLine = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
string actualEntry = string.Format(
CultureInfo.InvariantCulture,
"{{\"entry_name\":{0},\"writeline_declaring\":{1},\"has_readkey\":{2}}}",
JsonEscape(entry != null ? entry.Name : ""),
JsonEscape(writeLine != null ? writeLine.DeclaringType.FullName : ""),
typeof(Console).GetMethod("ReadKey", Type.EmptyTypes) != null ? "true" : "false"
);
string expectedEntry = "{\"entry_name\":\"Main\",\"writeline_declaring\":\"System.Console\",\"has_readkey\":true}";
cases.Add(MakeCase(
"main_entry_and_csc_workflow",
"反射校验程序集入口点 Main 以及 System.Console.WriteLine / ReadKey 方法定义",
expectedEntry,
actualEntry
));
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、count 与 Count 独立、注释不生效、且程序集入口点为 Main。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
当前源码 SHA256:5a6ca84ff211098823229426fad2512174a49ae05beb834cb0f9c76989ae8747
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
ZIP SHA256:df27279ebbc3de21ad3a9274f8bbf3f34131d1e1e1ca3044cf614be45a9e32a5
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
C# 的源文件名与其中 `public class` 的类名之间是否必须保持完全一致?这与 Java 有何区别?
展开参考解答
不必一致。Java 强制每个源文件中的 `public class` 必须与 `.java` 文件名严格同名;C# 编译器允许源文件名自由命名(如 `test.cs` 中定义 `HelloWorld` 类),但在团队工程中仍建议保持一致以便查阅。