C# 程序结构

C# 的最小的程序结构,以便作为接下来章节的参考

C# Hello World 实例

C# 程序主要包括以下部分

  • 命名空间声明(Namespace declaration)

  • 一个 class

  • Class 方法

  • Class 属性

  • 一个 Main 方法

  • 语句(Statements)& 表达式(Expressions)

  • 注释

打印 "Hello World" 代码

实例

using System;
namespace HelloWorldApplication
{
   class HelloWorld
   {
      static void Main(string[] args)
      {
         /* 我的第一个 C# 程序*/
         Console.WriteLine("Hello World");
         Console.ReadKey();
      }
   }
}

结果

Hello World

程序的各个部分

  • 程序的第一行 using System;   关键字using 在程序中包含 System 命名空间。一个程序可有多个 using 语句

  • namespace 声明。一个 namespace 里包含了一系列的类。HelloWorldApplication 命名空间包含了类 HelloWorld

  • class 声明。类 HelloWorld 包含了程序使用的数据和方法声明。类包含多个方法。方法定义类的行为。HelloWorld 类只有一个 Main 方法

  • Main 方法,C# 程序的 入口点Main 方法说明当执行时 类做什么动作

  •   会被编译器忽略,会在程序中添加额外的 注释

  • Main 方法通过语句 Console.WriteLine("Hello World"); 指定了它的行为

    WriteLine 定义在 System 命名空间中的 Console 类的一个方法。该语句在屏幕上显示消息 "Hello, World!"

  •  Console.ReadKey(); 针对 VS.NET 用户。使得程序会等待一个按键的动作,防止程序从 Visual Studio .NET 启动时屏幕会快速运行并关闭

注意点:

  • C# 大小写敏感

  • 语句和表达式必须以分号(;)结尾

  • 程序执行从 Main 方法开始

  • 文件名可以不同于类的名称

  • Main 方法必须定义为static

  • Main 首字母必须大写

  • 返回值是 void 或 int

  • 命令行参数可选

    static void Main(string[] args){}
    static void Main(){}
    static int Main(string[] args){}
    static int Main(){}

编译 & 执行 C# 程序

用 Visual Studio.Net 编译和执行 C# 程序 的步骤进行

  • 启动 Visual Studio

  • 菜单栏选择 File -> New -> Project

  • 模板中选择 Visual C#,选择 Windows

  • 选择 Console Application

  • 为项目制定名称,点击 OK 按钮

  • 新项目会出现在解决方案资源管理器(Solution Explorer)中

  • 代码编辑器(Code Editor)中编写代码

  • 点Run 按钮或按F5 键运行程序。出现命令提示符窗口(Command Prompt window)显示 Hello World

也可用命令行代替 Visual Studio IDE 来编译 C#

  • 打开文本编辑器,添加上面的代码

  • 保存文件为 helloworld.cs

  • 打开命令提示符,定位到文件所保存的目录

  • 键入 csc helloworld.cs 按 enter 键编译代码

  • 如果没有错误,命令提示符会进入下一行,生成 helloworld.exe 可执行文件

  • 键入 helloworld 执行程序

  • 看到  Hello World 打印在屏幕上