C# 作為強類型語言,類型轉換貫穿開發始終。本文系統梳理 C# 類型轉換的十大核心場景,涵蓋基礎類型別名、數值轉換、字符編碼、字符串處理、字節數組操作、日期時間轉換等實戰知識點,並附帶可直接運行的驗證代碼。
C# 關鍵字實為 .NET 基礎類型的別名,理解這層映射關係是掌握類型系統的基石:
| 關鍵字 | .NET 類型 | 說明 |
|---|---|---|
| bool | System.Boolean | 布爾值 |
| byte | System.Byte | 8 位無符號整數 (0-255) |
| sbyte | System.SByte | 8 位有符號整數 (-128~127) |
| char | System.Char | 16 位 Unicode 字符 |
| short | System.Int16 | 16 位有符號整數 |
| ushort | System.UInt16 | 16 位無符號整數 |
| int | System.Int32 | 32 位有符號整數 |
| uint | System.UInt32 | 32 位無符號整數 |
| long | System.Int64 | 64 位有符號整數 |
| ulong | System.UInt64 | 64 位無符號整數 |
| float | System.Single | 單精度浮點數 |
| double | System.Double | 雙精度浮點數 |
private void TestAlias() {
byte a = 1; char b = 'a'; short c = 1;
int d = 2; long e = 3; uint f = 4; bool g = true;
Console.WriteLine($"byte -> {a.GetType().FullName}");
Console.WriteLine($"char -> {b.GetType().FullName}");
Console.WriteLine($"short -> {c.GetType().FullName}");
Console.WriteLine($"int -> {d.GetType().FullName}");
Console.WriteLine($"long -> {e.GetType().FullName}");
Console.WriteLine($"uint -> {f.GetType().FullName}");
Console.WriteLine($"bool -> {g.GetType().FullName}");
}
// 輸出均為對應的 System.* 類型全名
按精度遞增方向自動轉換:byte → short → int → long → float → double
byte a = 1;
short b = a; // 隱式轉換
int c = b;
long d = c;
float e = d;
double f = e; // 所有值均為 1
逆向轉換需強制轉型,且可能導致數據截斷:
short g = 265;
byte h = (byte)g; // 結果為 9 (265 % 256)
Console.WriteLine(h); // 輸出 9
⚠️ 警告:強制轉換不拋出異常,靜默截斷高位數據,生產環境務必添加範圍檢查。
C# 採用 UTF-16 存儲字符,轉換遵循 C 風格強制轉型:
char ch = 'a';
short ascii = (short)ch; // 97
char fromAscii = (char)65; // 'A'
char cn = '中';
short unicode = (short)cn; // 20013
char fromUnicode = (char)22478; // '城'
float f = 54.321F;
string str = f.ToString(); // "54.321"
string str = "123";
int val = int.Parse(str); // 123
// 建議生產環境使用 TryParse 避免異常
if (int.TryParse(str, out int result)) { /* 成功 */ }
string str = "mytest";
char[] chars = str.ToCharArray(); // 長度 6
string fromChars = new string(chars); // "mytest"
// 單字符訪問更高效:char c = str[2]; // 't'
string s = "C#語言";
// ANSI 編碼(英文1字節,中文2字節)
byte[] ansiBytes = Encoding.Default.GetBytes(s); // 長度 6
// Unicode 編碼(統一2字節)
byte[] unicodeBytes = Encoding.Unicode.GetBytes(s); // 長度 8
// 解碼
string decoded = Encoding.ASCII.GetString(new byte[]{97,98,99}); // "abc"
使用 BitConverter 類進行底層內存操作:
int value = 12345;
byte[] bytes = BitConverter.GetBytes(value); // 4 字節
int restored = BitConverter.ToInt32(bytes, 0); // 12345
int a = 188;
Console.WriteLine(a.ToString("X")); // "BC" (大寫)
Console.WriteLine(a.ToString("x")); // "bc" (小寫)
Console.WriteLine(a.ToString("X4")); // "00BC" (補零)
// 解析十六進制字符串
int b = int.Parse("AB", NumberStyles.HexNumber); // 171
long ticks = DateTime.Now.Ticks;
DateTime dt = new DateTime(ticks);
double oaDate = DateTime.Now.ToOADate(); // 如 37494.6615
DateTime fromOA = DateTime.FromOADate(oaDate);
| 格式符 | 含義 | 示例 |
|---|---|---|
| yyyy | 四位年份 | 2024 |
| MM | 兩位月份 | 01-12 |
| dd | 兩位日期 | 01-31 |
| HH | 24制小時 | 00-23 |
| mm | 分鐘 | 00-59 |
| ss | 秒 | 00-59 |
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("yyyy-MM-dd HH:mm:ss")); // 2024-01-15 14:30:00
// 包含字面量文本需用引號轉義
Console.WriteLine(now.ToString("'Year:' yyyy 'Month:' MM")); // Year: 2024 Month: 01
TryParse 避免異常開銷BitConverter 或 BinaryPrimitives (.NET Core 2.1+)Encoding.UTF8)掌握這十大類型轉換場景,可覆蓋 95% 的業務開發需求。建議收藏備查,遇到具體問題查閱對應章節即可快速解決。