using System;
namespace Gosoa.Com
{
class MyFirstClass
{
static void Main()
{
Console.WriteLine("Hello World!");
}
}
}
編譯:csc test.cs → test.exe。關鍵點:
using System 引入基礎類別庫(類似 Java import)Main 為進入點,首字母大寫int i; // 整數變數
string str; // 字串變數
C# 強制變數在使用前必須被明確賦值,分兩種情境:
null/false 等型別預設值。// 類別欄位:合法,y 自動為 0
class Demo { static int y; static void Main() => Console.WriteLine(y); }
// 區域變數:編譯錯誤
static void Main() { int y; Console.WriteLine(y); } // CS0165
// 修正:顯式初始化
static void Main() { int y = 10; Console.WriteLine(y); }
作用域決定變數可被存取的程式碼區域:
{})結束。
// 合法:兩個 i 作用域分離
for (int i = 0; i < 10; i++) { }
for (int i = 0; i < 20; i++) { }
// 錯誤:外層 j 作用域覆蓋內層
int j = 5;
for (int i = 0; i < 10; i++)
{
int j = 20; // CS0136: 區域變數 'j' 無法在此範圍宣告
Console.WriteLine(i + j);
}
// 合法:區域變數遮蔽欄位
class Demo
{
int j = 30; // 欄位
static void Main()
{
int j = 20; // 區域變數遮蔽欄位
Console.WriteLine(j); // 輸出 20
}
}
const double PI = 3.14159;
const string AppName = "MyApp";
規則:
static,不可再加 static 關鍵字