C# 結合 C/C++ 效能與 Visual Basic 生產力,是 .NET 平台旗艦語言。本系列帶您從零建立扎實語法基礎,本集涵蓋第一支程式、自動記憶體管理、值/參考型別核心觀念。
using System;
class Hello
{
static void Main()
{
Console.WriteLine("Hello, world");
}
}
using System; 匯入 System 命名空間,簡化 System.Console 為 Consolestatic void Main() 或 static int Main(string[] args)#include,以組件參考取代文字包含csc hello.cs // 產生 hello.exe
hello.exe // 輸出 Hello, world
Finalize 執行時機public class Stack
{
private Node _first = null;
public bool Empty => _first == null;
public object Pop()
{
if (_first == null) throw new InvalidOperationException("Empty stack");
object val = _first.Value;
_first = _first.Next; // 釋放參考,Node 變不可達 → 符合 GC 回收資格
return val;
}
public void Push(object o) => _first = new Node(o, _first);
private class Node
{
public Node Next;
public object Value;
public Node(object v, Node n) { Value = v; Next = n; }
}
}
unsafe 關鍵字標記區塊/方法fixed 釘住陣列防止 GC 移動byte* p = &arr[0];/unsafe 參數,執行需 SecurityPermission| 類別 | 型別範例 | 儲存位置 | 指派語意 |
|---|---|---|---|
| 值型別 | int, double, bool, char, struct, enum | Stack (或內嵌於物件內) | 複製資料副本 |
| 參考型別 | class, interface, delegate, array, string | Heap (參考在 Stack) | 複製參考指向同一物件 |
// 值型別:各自獨立
int val1 = 0;
int val2 = val1; // 複製值
val2 = 123;
Console.WriteLine(val1); // 0
// 參考型別:共享物件
class Class1 { public int Value; }
var ref1 = new Class1();
var ref2 = ref1; // 複製參考
ref2.Value = 123;
Console.WriteLine(ref1.Value); // 123
// 列舉
public enum Color { Red, Blue, Green }
// 結構(值型別)
public struct Point { public int X, Y; }
// 介面
public interface IBase { void F(); }
public interface IDerived : IBase { void G(); }
// 類別(參考型別)
public class A { protected void H() => Console.WriteLine("A.H"); }
public class B : A, IDerived
{
public void F() => Console.WriteLine("B.F");
public void G() => Console.WriteLine("B.G");
}
// 委派
public delegate void EmptyDelegate();
Nullable<T>)掌握「類別包裹一切」、「GC 自動管理」、「值/參考型別語意差異」三大核心觀念,即可避開 C# 入門最大坑洞。下集將深入控制流程、方法、屬性等實務語法。