編譯器保證資訊不遺失、不會拋例外,自動發生:
byte n = byte.MaxValue; // 255
short n1 = n; // 255
int n2 = n; // 255
long n3 = n; // 255
// 方向:byte → short → int → long → float → double → decimal
// 以及衍生類別 → 基底類別、實作類別 → 介面
可能資訊遺失、可能拋例外,需開發者明確確認:
ulong n = ulong.MaxValue; // 18446744073709551615
byte n1 = (byte)n; // 255 (截尾)
ushort n2 = (ushort)n; // 65535 (截尾)
uint n3 = (uint)n; // 4294967295 (截尾)
// 方向:double → float → long → int → short → byte 等縮小轉換
| 方式 | 適用 | 失敗行為 |
|---|---|---|
| Cast `(T)` | 基本型別、參考型別之間 | 例外/截尾 |
| `Convert.ToXxx` | 物件/字串 → 基本型別 | 例外 (可捕捉) |
| `TryParse` | 字串 → 數值 | 回傳 `false`,不拋例外 |
| `as` | 參考型別向下轉型 | 回傳 `null` |
| `is` | 型別測試 (C# 7+ 型別模式) | 回傳 `bool` |
類別/結構可定義 `implicit`/`explicit` 運算子:
public struct Digit
{
public byte Value;
public static implicit operator byte(Digit d) => d.Value;
public static explicit operator Digit(byte b) => new Digit { Value = b };
}