首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 裝箱拆箱與型別別名完整指南(一):關鍵字對應 System 型別、範圍與實驗程式碼

     編輯:關於C語言

什麼是「別名」?

C# 是徹底的物件導向語言,所有「基本型別」實際上都是 System 命名空間下的結構體(struct)。為了程式碼可讀性,C# 提供關鍵字作為這些型別的別名:

完整對照表

C# 關鍵字.NET 型別說明大小/範圍
boolSystem.Boolean布林值true/false
charSystem.CharUnicode 字元2 bytes
byteSystem.Byte無號位元組0~255
sbyteSystem.SByte有號位元組-128~127
ushortSystem.UInt16無號短整數0~65,535
uintSystem.UInt32無號整數0~4,294,967,295
ulongSystem.UInt64無號長整數0~1.8×10¹⁹
shortSystem.Int16有號短整數-32,768~32,767
intSystem.Int32有號整數-2,147,483,648~2,147,483,647
longSystem.Int64有號長整數±9.22×10¹⁸
floatSystem.Single單精度浮點數4 bytes
doubleSystem.Double雙精度浮點數8 bytes

裝箱與拆箱

  • 裝箱:實值型別 → object(參考型別),配置堆疊記憶體並複製值。
  • 拆箱:object → 實值型別,需型別檢查並複製回堆疊。
  • C# 編譯器自動處理,開發者無需手動干預,但效能成本較高(記憶體配置、GC 壓力),熱路徑應避免頻繁裝箱。

驗證實驗程式碼

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)所示輸出,確認別名與型別對應關係。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved