C# 的基本型別(int、double、bool 等)實際上是結構體,對應 System.Int32、System.Double、System.Boolean 等類型。所謂「裝箱/拆箱」實際上是值型別與 object 之間的轉換,而 int ⇄ Int32 僅是編譯期的別名關係,零成本:
int a = 1;
Console.WriteLine(a.GetType().FullName); // System.Int32
常用別名對照表:
| 關鍵字 | 完整型別 | 大小/範圍 |
|---|---|---|
| bool | System.Boolean | true/false |
| byte | System.Byte | 0~255 |
| sbyte | System.SByte | -128~127 |
| char | System.Char | UTF-16 字元 |
| short | System.Int16 | -32,768~32,767 |
| ushort | System.UInt16 | 0~65,535 |
| int | System.Int32 | -2,147,483,648~2,147,483,647 |
| uint | System.UInt32 | 0~4,294,967,295 |
| long | System.Int64 | ±9.22×10¹⁸ |
| ulong | System.UInt64 | 0~1.84×10¹⁹ |
| float | System.Single | 7 位有效數字 |
| double | System.Double | 15-16 位有效數字 |
| decimal | System.Decimal | 28-29 位有效數字,金融首選 |
隱式轉換(資料不會遺失):byte → short → int → long → float → double
byte b = 100;
int i = b; // 隱式
long l = i; // 隱式
顯式轉換(可能遺失資料或溢位):
int i = 300;
byte b = (byte)i; // 44 (300 % 256) - 溢位截斷!
檢查溢位:使用 checked 區塊或編譯選項 /checked+ 讓溢位拋出 OverflowException。
char c = 'A';
int ascii = (int)c; // 65
char fromCode = (char)65; // 'A'
char chinese = '中';
int unicode = (int)chinese; // 20013 (0x4E2D)
// 數值 → 字串
string s1 = 123.ToString();
string s2 = 3.14.ToString("F2"); // "3.14"
string hex = 255.ToString("X4"); // "00FF"
// 字串 → 數值
int i = int.Parse("123");
double d = double.Parse("3.14", CultureInfo.InvariantCulture);
bool success = int.TryParse("abc", out int result); // 安全轉換
string text = "Hello";
// 字串 → char[]
char[] chars = text.ToCharArray();
// char[] → 字串
string fromChars = new string(chars);
// 字串 → byte[] (指定編碼)
byte[] utf8Bytes = Encoding.UTF8.GetBytes(text);
byte[] big5Bytes = Encoding.GetEncoding("big5").GetBytes(text);
// byte[] → 字串
string fromUtf8 = Encoding.UTF8.GetString(utf8Bytes);
int value = 0x01020304;
byte[] bytes = BitConverter.GetBytes(value); // 小端序:04 03 02 01
int restored = BitConverter.ToInt32(bytes, 0);
int n = 188;
Console.WriteLine(n.ToString("X")); // "BC"
Console.WriteLine(n.ToString("X4")); // "00BC"
int parsed = int.Parse("BC", NumberStyles.HexNumber); // 188
// DateTime → long (Ticks: 100ns 間隔從 0001-01-01 起算)
long ticks = DateTime.Now.Ticks;
DateTime dt = new DateTime(ticks);
// DateTime ↔ Double (OLE Automation Date: 從 1899-12-30 起算的天數)
double oaDate = DateTime.Now.ToOADate();
DateTime fromOA = DateTime.FromOADate(oaDate);
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("yyyy-MM-dd HH:mm:ss")); // 2024-01-15 14:30:45
Console.WriteLine(now.ToString("yyyy年M月d日")); // 2024年1月15日
// 包含字面文字需用單引號跳脫
Console.WriteLine(now.ToString("'Year:' yyyy 'Month:' MM")); // Year: 2024 Month: 01
常用格式字元:y/M/d(無前導零)、yy/MM/dd(有前導零)、HH/mm/ss(24小時制)、hh/mm/ss(12小時制)、fff(毫秒)。