using System;
class Welcome {
static void Main() {
Console.WriteLine("Please enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Welcome to you, {0}!", name);
}
}
using System;
匯入 System 命名空間,得以直接使用 Console 等類別。未引入時需寫完整名稱 System.Console。
Main() 為程式進入點,必須為 static,回傳 void 或 int。| 方法 | 用途 | 換行 |
|---|---|---|
Console.WriteLine | 輸出並換行 | 是 |
Console.Write | 輸出不換行 | 否 |
Console.ReadLine | 讀取一行文字 | 含換行 |
Console.Read | 讀取單一字元代碼 | 否 |
Console.WriteLine("Welcome {0} times, {1} and {2}!", x, name1, name2);
{0}, {1} 為佔位符,對應後續參數。csc Welcome.cs // 產生 Welcome.exe
csc /out:MyApp.exe Welcome.cs // 指定輸出檔名
csc /target:library Util.cs // 產生 DLL
csc /? // 顯示所有選項
C# 編譯器直接產生 EXE/DLL,無獨立連結步驟(不同於 C/C++)。
// 單行註解
/* 多行
註解 */
// 後使用 \(續行符會導致下一行也被註解)。/* */ 不可巢狀,建議用 #if false ... #endif 暫時停用含註解的程式碼區塊。string s = "Good" + "Morning"; // 串接
char c = s[3]; // 索引存取,得 'd'