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

C# 語言未來功能展望 (2):泛型基本語法與優勢

     編輯:關於C語言

傳統 Stack 缺點

  • 以 object 儲存,值型別須裝箱/拆箱,效能損耗大。
  • 無型別限制,執行期才發現轉型錯誤。

泛型 Stack 定義與使用

public class Stack<ItemType>
{
    private ItemType[] items;
    public void Push(ItemType data) { ... }
    public ItemType Pop() { ... }
}

Stack<int> s = new Stack<int>();
s.Push(3);
int x = s.Pop(); // 無需轉型,無裝箱

Stack<Customer> s2 = new Stack<Customer>();
s2.Push(new Customer());
Customer c = s2.Pop(); // 型別安全
// s2.Push(3); // 編譯錯誤

泛型優勢

  1. 型別安全:編譯期檢查。
  2. 效能:值型別避免裝箱/拆箱。
  3. 程式碼重用:單一定義支援多型別。
  4. 可讀性:意圖明確。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved