共用方式為


Visual C# 中的 Hello World

以下是 Hello World 在 Visual C# 中的樣子:

清單 1:Visual C# 中的 Hello World (HelloCS.cs)

// Allow easy reference to the System namespace classes.
using System;

// This class exists only to house the entry point.
class MainApp {
   // The static method, Main, is the application's entry point.
   public static void Main() {
      // Write text to the console.
      Console.WriteLine("Hello World using C#!");
   }
}

這個程式碼比 Managed Extensions for C++ 中對等的程式碼長。存取核心程式庫的語法是新的;它會指定命名空間,而非它所在的檔案名稱:

using System;

最大的差異是類別規格 (Class Specification):

class MainApp {

在 Visual C# 中,所有程式碼都包含在類別的方法中。因此,若要儲存進入點程式碼,必須先建立類別(此處類別的名稱不重要)。接著,請指定進入點:

public static void Main () {

編譯器會要求將這個進入點命名為 Main。也必須將進入點同時標記為 publicstatic。此外,和 Managed Extensions for C++ 的範例一樣,進入點沒有使用引數,也不會傳回任何值 (但是較複離的程式當然可以使用不同的簽名碼)。

下一行是:

Console.WriteLine("Hello World using C#!");      

同樣地,這一行也會使用 Runtime Console 型別輸出字串。但是在 Visual C# 中,您可以使用句點 (.) 來表示範圍。此外,您也不需要在字串前面加上 L,因為 C# 中的所有字串都是 Unicode。

Build.bat 檔案中只要包含下列這一行,就可以建置這個程式:

csc.exe /debug+ /out:.\HelloCS.exe helloCS.cs

在這個公認簡單的範例中,除了要編譯的檔案以外,您不必指定其他任何項目。特別是,C# 不會使用 C++ 所需要的其他連結步驟:

C:\...\HelloWorld\cs>build
C:\...\HelloWorld\cs>csc.exe /debug+ /out:.\HelloCS.exe hellocs.cs
Microsoft (R) Visual C# Compiler Version ...[CLR version...]
Copyright (C) Microsoft Corp 2000-2001. All rights reserved.

C# 編譯器的預設輸出是名稱相同的可執行檔,執行這個程式會產生下列輸出:

C:\...\HelloWorld\cs>hellocs
Hello World using Visual C#!

請參閱

Visual Basic 中的 Hello World | 撰寫簡單的 .NET 元件 | 簡單元件的用戶端 | 開發教學課程摘要 | 附錄 A:瀏覽命名空間的工具