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

C# 語言未來功能展望 (4):泛型約束與執行期實例化

     編輯:關於C語言

泛型約束

使用 where 關鍵字限定型別參數需實作介面或繼承類別:

public class Dictionary<KeyType, ValType> where KeyType : IComparable
{
    public void Add(KeyType key, ValType val)
    {
        switch (key.CompareTo(x)) { ... } // 無需轉型
    }
}

多重約束

public class Dictionary<KeyType, ValType>
    where KeyType : IComparable, IEnumerable
    where ValType : Customer
{ ... }

執行期實例化機制

  • 值型別參數:每個唯一值型別產生專屬具體型別(如 Stack<int>),效能最佳,無裝箱。
  • 參考型別參數:共用單一具體型別實作(如 Stack<string>、Stack<Customer> 共用程式碼)。

範例

Stack<int> s1 = new Stack<int>();
Stack<int> s2 = new Stack<int>(); // 重用同一具體型別
Stack<long> s3 = new Stack<long>(); // 另產生長整數版本
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved