C#-泛型類型(十六)


概述
  泛型類和泛型方法兼具可重用性、類型安全性和效率,這是非泛型類和非泛型方法無法實現的
  泛型通常與集合以及作用於集合的方法一起使用
   泛型所屬命名空間:System.Collections.Generic 
  可以創建自定義泛型接口、泛型類、泛型方法、泛型事件和泛型委托,以提供自己的通用解決方案,設計類型安全的高效模式
  泛型允許編寫一個可以與任何數據類型一起工作的類或方法
 
示例
 
 1 using System;
 2 using System.Collections.Generic;
 3 
 4 namespace GenericTest
 5 {
 6     public class TestGeneric<T>
 7     {
 8         
 9         private T[] array;
10         public TestGeneric(int i)
11         {
12             array = new T[i + 1];
13         }
14         public T GetItem(int index)
15         {
16             return array[index];
17         }
18         public void setItem(int index, T value)
19         {
20             array[index] = value;
21         }
22     }
23 
24     class Tester
25     {
26         static void Main(string[] args)
27         {
28             TestGeneric<char> MyArray = new TestGeneric<char>(5);
29             for (int i = 0; i < 5; i++)
30             {
31                 MyArray.setItem(i, (char)(i + 97));
32             }
33 
34             for (int i=0; i<5; i++)
35             {
36                 Console.WriteLine(MyArray.GetItem(i));
37             }
38             Console.WriteLine();
39             Console.ReadKey();
40         }
41 
42     }
43 }

 

結果

 

約束

  對代碼能夠在實例化類時用於類型參數的類型種類施加限制
  約束的方式是指定T的祖先,即繼承的接口或類
  代碼嘗試使用某個約束所不允許的類型來實例化類,則會產生編譯時錯誤
  定義:public T GetInfo<T>(string id) where T : CBaseInfo
 

約束限定條件

  •  T:struct    類型參數必須是值類型。可以指定除 Nullable 以外的任何值類型
  •  T:class      類型參數必須是引用類型,包括任何類、接口、委托或數組類型
  •  T:new()      類型參數必須具有無參數的公共構造函數。當與其他約束一起使用時new() 約束必須最后指定
  •  T:<基類名> 類型參數必須是指定的基類或派生自指定的基類
  •  T:<接口名稱> 類型參數必須是指定的接口或實現指定的接口。可以指定多個接口約束。約束接口也可以是泛型的。
  •  T:U    為 T 提供的類型參數必須是為 U 提供的參數或派生自為 U 提供的參數,稱為裸類型約束

例:

public class Myarray<T> : B<T> where T : new() { }

定義多個類型參數和約束:

public class Base<A,B,C> where A: struct
where B: new()
where C: class
{ }

泛型也可以繼承泛型:

class D:C<string,int>

class E<U,V>:C<U,V>

class F<U,V>:C<string,int>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM