C# 程序的基本结构是什么?
csharpprogrammingserver side programming更新于 2025/10/14 7:37:17
我们先来看一个 C# 示例程序 −
using System;
namespace DemoApplication {
class HelloWorld {
static void Main(string[] args) {
Console.WriteLine("Welcome!");
Console.ReadKey();
}
}
}
现在让我们看看上面的程序都包含了什么 −
using
程序的第一行使用 System; - using 关键字用于在程序中包含 System 命名空间。一个程序通常包含多个 using 语句。
命名空间声明
下一行是命名空间声明。命名空间是类的集合。DemoApplication 命名空间包含 HelloWorld 类。
类声明
下一行是类声明,类 HelloWorld 包含程序使用的数据和方法定义。类通常包含多个方法。方法定义了类的行为。但是,HelloWorld 类只有一个 Main 方法。
Main 方法
下一行定义了 Main 方法,它是所有 C# 程序的入口点。Main 方法声明了该类在执行时执行的操作。
Console.WriteLine
Main 方法使用语句 Console.WriteLine("Welcome!"); 指定其行为。
WriteLine 是 System 命名空间中定义的 Console 类的一个方法。此语句会在屏幕上显示消息"Welcome!"。
Console.ReadKey()
最后一行 Console.ReadKey(); 适用于 VS.NET 用户。这会使程序等待按键,并防止从 Visual Studio .NET 启动程序时屏幕快速运行和关闭。

