| 類型 | 關鍵字/方法 | 特性 | 範例 |
|---|---|---|---|
| 隱含轉換 | 自動 | 無資料遺失、編譯器保證安全 | int i = 10; long l = i; |
| 顯性轉換 | (T) / Convert.ToX | 可能資料遺失/溢位、需開發者確認 | int i = (int)l; int i = Convert.ToInt32(l); |
| 解析/格式化 | Parse/TryParse | 字串↔數值、TryParse 不拋例外 | int.TryParse("123", out int v) |
| as 運算子 | as | 參考型別安全轉換、失敗回傳 null | var s = obj as string; |
| is 型別模式 | is | C# 7+ 模式比對、宣告變數 | if (obj is int i) ... |
| 使用者定義 | implicit/explicit operator | 自訂型別間轉換 | public static implicit operator MyType(int v) |
sbyte → short → int → long → float → double
byte → short → int → long → float → double
→ ushort → uint → ulong → float → double
char → ushort → uint → ulong → float → double
無符號→有符號需顯性轉換 (可能溢位)。float→double 隱含,double→float 顯性。
// 未檢查溢位 (預設)
int i = 2_000_000_000;
int j = i * 2; // 溢位回繞 -294967296
// 檢查溢位區塊
checked {
int k = i * 2; // 拋 OverflowException
}
// 編譯器選項 /checked+ 整個專案啟用
// Parse: 失敗拋 FormatException/OverflowException
int v1 = int.Parse("123"); // 正常
// int v2 = int.Parse("abc"); // 例外
// TryParse: 失敗回傳 false,不拋例外 (高效能)
if (int.TryParse(input, out int v3)) {
// 成功
}
// Span 版本 (C# 7.2+) 避免字串配置
ReadOnlySpan span = "123".AsSpan();
int.TryParse(span, out int v4);
// 傳統 as + null 檢查
var str = obj as string;
if (str != null) Console.WriteLine(str.Length);
// C# 7+ is 型別模式 (單一陳述式)
if (obj is string s) Console.WriteLine(s.Length);
// 進階模式
if (obj is int i and > 0) Console.WriteLine($"正整數: {i}");
if (obj is IEnumerable nums) Console.WriteLine(nums.Count());
// switch 運算式結合型別模式
string desc = obj switch {
int i => $"Int: {i}",
string s => $"String: {s}",
null => "Null",
_ => "Other"
};
public readonly struct Temperature {
public double Celsius { get; }
public Temperature(double c) => Celsius = c;
// 隱含:int → Temperature (安全)
public static implicit operator Temperature(int c) => new Temperature(c);
// 顯性:Temperature → int (可能遺失精度)
public static explicit operator int(Temperature t) => (int)Math.Round(t.Celsius);
// 使用
Temperature t1 = 25; // 隱含
int c = (int)t1; // 顯性
}
Convert.ToX (虛擬呼叫、格式提供者開銷),優先 Parse/TryParse 或直接轉型as 僅適用參考型別,實值型別用 Nullable<T> 或模式比對Span / Utf8Parser (System.Buffers.Text) 零複製



