型別轉換是日常開發高頻操作。本文系統整理 Convert 類別方法表、隱式/顯式轉換規則、checked/unchecked 溢位控制與最佳實務。
| 方法 | 目標型別 |
|---|---|
| ToBoolean | bool |
| ToByte | byte |
| ToChar | char |
| ToDateTime | DateTime |
| ToDecimal | decimal |
| ToDouble | double |
| ToInt16 | short |
| ToInt32 | int |
| ToInt64 | long |
| ToSByte | sbyte |
| ToSingle | float |
| ToString | string |
| ToUInt16 | ushort |
| ToUInt32 | uint |
| ToUInt64 | ulong |
using System;
class MyClass
{
static void Main()
{
int num;
string str;
num = 99;
str = Convert.ToString(num); // 數值轉字串
Console.WriteLine(str); // "99"
str = "123";
num = Convert.ToInt32(str); // 字串轉數值
Console.WriteLine(num); // 123
Console.ReadKey();
}
}
目標型別範圍大於來源型別時,編譯器自動完成,無資料遺失風險。
using System;
class MyClass
{
static void Main()
{
byte n = byte.MaxValue; // 255
short n1 = n; // 隱式轉換
int n2 = n;
long n3 = n;
Console.WriteLine("{0},{1},{2}", n1, n2, n3); // 255,255,255
Console.ReadKey();
}
}
目標型別範圍較小,可能發生資料截斷或溢位,需開發者明確指示。
using System;
class MyClass
{
static void Main()
{
ulong n = ulong.MaxValue; // 18446744073709551615
byte n1 = (byte)n; // 截取低 8 位 -> 255
ushort n2 = (ushort)n; // 截取低 16 位 -> 65535
uint n3 = (uint)n; // 截取低 32 位 -> 4294967295
Console.WriteLine("{0},{1},{2}", n1, n2, n3);
Console.ReadKey();
}
}
OverflowException。using System;
class MyClass
{
static void Main()
{
int i;
byte b;
i = 255;
b = (byte)i; // 未超出 byte 範圍,正常
b = unchecked((byte)i); // 同前,不檢查
Console.WriteLine(b); // 255
i++; // 256
b = (byte)i; // 預設 unchecked,截位 -> 0
b = unchecked((byte)i); // 同前
Console.WriteLine(b); // 0
i = 255;
b = checked((byte)i); // 明確檢查,通過
Console.WriteLine(b); // 255
i++; // 256
try
{
b = checked((byte)i); // 觸發 OverflowException
Console.WriteLine(b);
}
catch (OverflowException ex)
{
Console.WriteLine("溢位錯誤: " + ex.Message);
}
Console.ReadKey();
}
}
Convert 類別進行字串與基礎型別互轉,可處理 null 且語意清晰。checked 確保資料正確性。unchecked 避免檢查開銷,但需確定資料範圍安全。