C# 無全域變數/函數。所有代碼必須在類別內。習慣 C/C++ 的開發者請暫時忘記全域概念。
class Welcome
{
static void Main() // 程式進入點,固定名稱,必須 static
{
// 程式邏輯從這裡開始
}
}
class Welcome:宣告類別,內容包在 { } 中,大括號必須成對static void Main():進入點,void 表無回傳值,() 可接參數MainConsole 為 System 命名空間預定義類別:
| 方法 | 行為 | 回傳值 |
|---|---|---|
WriteLine() | 輸出後換行 | void |
Write() | 輸出不換行 | void |
ReadLine() | 讀取一行文字 | string |
Read() | 讀取單一字元 | int (字元代碼) |
using System;
class Welcome
{
static void Main()
{
Console.WriteLine("Please enter your name:");
string name = Console.ReadLine(); // 宣告並指派
Console.WriteLine("Welcome to you, {0}!", name); // 格式化輸出
}
}
{0}、{1}...{0} 由第二參數取代,{1} 由第三參數取代,最多三個int x = 3;
string n1 = "Mike", n2 = "John";
Console.WriteLine("Welcome {0} times, {1} and {2}!", x, n1, n2);
// 輸出:Welcome 3 times, Mike and John!
string 操作string 為參考型別,標準字元集,支援豐富操作:
// 連接
string s = "Good" + "Morning"; // "GoodMorning"
// 索引存取(唯讀)
char c = s[3]; // 'd'(索引從 0 開始)
// 其他常用:Substring、Split、Replace、Trim、ToUpper/Lower 等
string message = "Welcome to you" + Console.ReadLine();
Console.WriteLine(message);
功能相同,風格差異。建議優先使用格式化字串,可讀性較佳。
using System 的作用未 using System 時,需完整寫 System.Console.WriteLine。. 表成員存取,取代 C++ ::/->。System 為 .NET 最基礎命名空間之一。