C# 關鍵字實為結構體別名,編譯後均為對應結構體:
| 關鍵字 | 結構體 | 說明 |
|---|---|---|
| bool | System.Boolean | true/false |
| byte | System.Byte | 0~255 |
| sbyte | System.SByte | -128~127 |
| char | System.Char | Unicode 字符 |
| short | System.Int16 | -32,768~32,767 |
| ushort | System.UInt16 | 0~65,535 |
| int | System.Int32 | -2.1B~2.1B |
| uint | System.UInt32 | 0~4.2B |
| long | System.Int64 | ±9.22E18 |
| ulong | System.UInt64 | 0~1.84E19 |
| float | System.Single | 7位精度 |
| double | System.Double | 15-16位精度 |
| decimal | System.Decimal | 28-29位精度,貨幣首選 |
驗證代碼:typeof(int) == typeof(System.Int32) → true
(targetType)value,可能溢出或精度損失checked 上下文拋出 OverflowException
// 字符 → 編碼
char ch = 'A';
int ascii = (int)ch; // 65
char cn = '中';
int unicode = (int)cn; // 20013
// 編碼 → 字符
char fromAscii = (char)65; // 'A'
char fromUnicode = (char)20013; // '中'
value.ToString()、string.Format、$"{value}"int.Parse("123")、int.TryParse(推薦,避免異常)、Convert.ToInt32| 轉換 | 方法 |
|---|---|
| String → char[] | str.ToCharArray() |
| char[] → String | new string(charArray) |
| String → byte[] | Encoding.UTF8.GetBytes(str) |
| byte[] → String | Encoding.UTF8.GetString(bytes) |
常用編碼:Encoding.Default (ANSI)、Encoding.Unicode (UTF-16 LE)、Encoding.UTF8、Encoding.ASCII
byte[] bytes = BitConverter.GetBytes(12345); // int → 4 bytes
int value = BitConverter.ToInt32(bytes, 0); // 4 bytes → int
int val = 188;
val.ToString("X"); // "BC"
val.ToString("X4"); // "00BC" (寬度4,前導0)
int parsed = int.Parse("BC", NumberStyles.HexNumber); // 188
Ticks:從 0001-01-01 00:00:00 起的 100ns 間隔數,long ticks = dt.Ticks,new DateTime(ticks)double oa = dt.ToOADate(),DateTime.FromOADate(oa)| 符號 | 含義 | 示例 |
|---|---|---|
| yyyy | 四位年 | 2024 |
| MM | 兩位月 | 01~12 |
| dd | 兩位日 | 01~31 |
| HH | 24制時 | 00~23 |
| mm | 分 | 00~59 |
| ss | 秒 | 00~59 |
| fff | 毫秒 | 000~999 |
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // 2024-01-15 14:30:45
DateTime.Now.ToString("'Year:' yyyy 'Month:' MM"); // Year: 2024 Month: 01
字面量文字用單引號或雙引號包裹。