C# 是徹底的物件導向語言,所有「基本型別」實際上都是 System 命名空間下的結構體(struct)。為了程式碼可讀性,C# 提供關鍵字作為這些型別的別名:
| C# 關鍵字 | .NET 型別 | 說明 | 大小/範圍 |
|---|---|---|---|
| bool | System.Boolean | 布林值 | true/false |
| char | System.Char | Unicode 字元 | 2 bytes |
| byte | System.Byte | 無號位元組 | 0~255 |
| sbyte | System.SByte | 有號位元組 | -128~127 |
| ushort | System.UInt16 | 無號短整數 | 0~65,535 |
| uint | System.UInt32 | 無號整數 | 0~4,294,967,295 |
| ulong | System.UInt64 | 無號長整數 | 0~1.8×10¹⁹ |
| short | System.Int16 | 有號短整數 | -32,768~32,767 |
| int | System.Int32 | 有號整數 | -2,147,483,648~2,147,483,647 |
| long | System.Int64 | 有號長整數 | ±9.22×10¹⁸ |
| float | System.Single | 單精度浮點數 | 4 bytes |
| double | System.Double | 雙精度浮點數 | 8 bytes |
object(參考型別),配置堆疊記憶體並複製值。object → 實值型別,需型別檢查並複製回堆疊。private void TestAlias()
{
byte a = 1; char b = 'a'; short c = 1;
int d = 2; long e = 3; uint f = 4; bool g = true;
textBox1.Text = "";
textBox1.AppendText($"byte -> {a.GetType().FullName}\n");
textBox1.AppendText($"char -> {b.GetType().FullName}\n");
textBox1.AppendText($"short -> {c.GetType().FullName}\n");
textBox1.AppendText($"int -> {d.GetType().FullName}\n");
textBox1.AppendText($"long -> {e.GetType().FullName}\n");
textBox1.AppendText($"uint -> {f.GetType().FullName}\n");
textBox1.AppendText($"bool -> {g.GetType().FullName}\n");
}
執行結果即為上一篇(ID 81094)所示輸出,確認別名與型別對應關係。