string s1 = "A string";
string s2 = s1; // 參考同一字串物件
s1 = "Another string"; // s1 指向新物件,s2 不受影響
// 輸出結果:
// s1 is A string
// s2 is A string
// s1 is now Another string
// s2 is now A string
字串為參考型別但具值語意(不可變)。指派操作實際是建立新字串物件,原物件不變。這與 C/C++ 指標行為截然不同。
// 傳統逸出:雙反斜線
string path1 = "C:\\Program Files\\MyApp";
// 逐字字串:@ 前綴,保留原始字元(含換行)
string path2 = @"C:\Program Files\MyApp";
string multiLine = @"第一行
第二行
第三行";
public struct Subscriber
{
public long SubscriberID;
public string FirstName;
public string MiddleName;
public string LastName;
public decimal Balance;
}
// 使用方式
var sub1 = new Subscriber(); // 可選 new,欄位自動歸零
sub1.FirstName = "John";
sub1.Balance = 100;
var sub2 = sub1; // 值拷貝,sub2 獨立於 sub1
sub2.Balance = 200; // 不影響 sub1
關鍵差異:
ValueType)
public enum TimeOfDay
{
Morning = 0,
Afternoon = 1,
Evening = 2
}
public static void WriteGreeting(TimeOfDay time)
{
switch (time)
{
case TimeOfDay.Morning:
Console.WriteLine("Good morning!");
break;
case TimeOfDay.Afternoon:
Console.WriteLine("Good afternoon!");
break;
case TimeOfDay.Evening:
Console.WriteLine("Good evening!");
break;
default:
Console.WriteLine("Hello!");
break;
}
}
列舉底層為整數型別(預設 int),可指定基底型別:enum Color : byte { Red, Green, Blue }。
// 一維陣列
int[] a = new int[32];
a[0] = 35;
a[31] = 322;
string[] c = { "a", "b", "c" }; // 隱含 new
string[] d = new string[] { "a", "b", "c" }; // 顯式 new
// 多維陣列(矩形)
int[,] matrix = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
// 交錯陣列
string[][] lists = new string[3][];
lists[0] = new string[] { "a", "b", "c" };
lists[1] = new string[] { "d", "e", "f" };
lists[2] = new string[] { "g", "h", "i" };
// 遍歷交錯陣列
for (int i = 0; i < lists.GetLength(0); i++)
{
for (int j = 0; j < lists[i].GetLength(0); j++)
Console.Write(lists[i][j] + ",");
Console.WriteLine();
}
| 規則 | 說明 |
|---|---|
| 索引從 0 開始 | 長度 N 的陣列,有效索引 0 ~ N-1 |
| 初始化需用 new | 除隱含初始化語法外 |
| 支援動態大小 | new int[n] 其中 n 為變數 |
| 大括號初始化 | { "a", "b" } 類似 Java |
| 長度不可用變數指定於大括號語法 | new string[len] { ... } 錯誤,需 const int len |
| 初始化元素數需匹配宣告大小 | new string[3] { "a", "b", "c", "d" } 編譯錯誤 |
| 方括號宣告 | int[] a 而非 int a[] (C 風格) |
string[] arr = { "Linda", "Lily", "Adidas" };
int len = arr.Length; // 總長度
int dimLen = arr.GetLength(0); // 第 0 維長度
Array.Sort(arr); // 靜態方法排序
Array.Reverse(arr); // 靜態方法反轉
陣列隱含實作 IList、ICollection、IEnumerable,可直接用於 foreach、LINQ 查詢。
複合參考型別的核心——類別(封裝、繼承、多型)、介面(契約)、委派(事件基礎)將是後續學習重點。