国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C# > 正文

深入解析C#中的泛型類與泛型接口

2020-01-24 01:17:06
字體:
供稿:網(wǎng)友

泛型類

泛型類封裝不是特定于具體數(shù)據(jù)類型的操作。泛型類最常用于集合,如鏈接列表、哈希表、堆棧、隊(duì)列、樹等。像從集合中添加和移除項(xiàng)這樣的操作都以大體上相同的方式執(zhí)行,與所存儲(chǔ)數(shù)據(jù)的類型無關(guān)。
對(duì)于大多數(shù)需要集合類的方案,推薦的方法是使用 .NET Framework 類庫(kù)中所提供的類。

  • 一般情況下,創(chuàng)建泛型類的過程為:從一個(gè)現(xiàn)有的具體類開始,逐一將每個(gè)類型更改為類型參數(shù),直至達(dá)到通用化和可用性的最佳平衡。創(chuàng)建您自己的泛型類時(shí),需要特別注意以下事項(xiàng):
  • 將哪些類型通用化為類型參數(shù)。
  • 通常,能夠參數(shù)化的類型越多,代碼就會(huì)變得越靈活,重用性就越好。但是,太多的通用化會(huì)使其他開發(fā)人員難以閱讀或理解代碼。
  • 如果存在約束,應(yīng)對(duì)類型參數(shù)應(yīng)用什么約束。
  • 一條有用的規(guī)則是,應(yīng)用盡可能最多的約束,但仍使您能夠處理必須處理的類型。例如,如果您知道您的泛型類僅用于引用類型,則應(yīng)用類約束。這可以防止您的類被意外地用于值類型,并允許您對(duì) T 使用 as 運(yùn)算符以及檢查空值。
  • 是否將泛型行為分解為基類和子類。
  • 由于泛型類可以作為基類使用,此處適用的設(shè)計(jì)注意事項(xiàng)與非泛型類相同。請(qǐng)參見本主題后面有關(guān)從泛型基類繼承的規(guī)則。
  • 是否實(shí)現(xiàn)一個(gè)或多個(gè)泛型接口。

例如,如果您設(shè)計(jì)一個(gè)類,該類將用于創(chuàng)建基于泛型的集合中的項(xiàng),則可能必須實(shí)現(xiàn)一個(gè)接口,如 IComparable<T>,其中 T 是您的類的類型。

類型參數(shù)和約束的規(guī)則對(duì)于泛型類行為有幾方面的含義,特別是關(guān)于繼承和成員可訪問性。您應(yīng)當(dāng)先理解一些術(shù)語(yǔ),然后再繼續(xù)進(jìn)行。對(duì)于泛型類 Node<T>,客戶端代碼可通過指定類型參數(shù)來引用該類,以便創(chuàng)建封閉式構(gòu)造類型 (Node<int>)?;蛘呖梢宰岊愋蛥?shù)處于未指定狀態(tài)(例如在指定泛型基類時(shí))以創(chuàng)建開放式構(gòu)造類型 (Node<T>)。泛型類可以從具體的、封閉式構(gòu)造或開放式構(gòu)造基類繼承:

class BaseNode { }class BaseNodeGeneric<T> { }// concrete typeclass NodeConcrete<T> : BaseNode { }//closed constructed typeclass NodeClosed<T> : BaseNodeGeneric<int> { }//open constructed type class NodeOpen<T> : BaseNodeGeneric<T> { }

非泛型類(換句話說,即具體類)可以從封閉式構(gòu)造基類繼承,但無法從開放式構(gòu)造類或類型參數(shù)繼承,因?yàn)樵谶\(yùn)行時(shí)客戶端代碼無法提供實(shí)例化基類所需的類型參數(shù)。

//No errorclass Node1 : BaseNodeGeneric<int> { }//Generates an error//class Node2 : BaseNodeGeneric<T> {}//Generates an error//class Node3 : T {}

從開放式構(gòu)造類型繼承的泛型類必須為任何未被繼承類共享的基類類型參數(shù)提供類型變量,如以下代碼所示:

class BaseNodeMultiple<T, U> { }//No errorclass Node4<T> : BaseNodeMultiple<T, int> { }//No errorclass Node5<T, U> : BaseNodeMultiple<T, U> { }//Generates an error//class Node6<T> : BaseNodeMultiple<T, U> {} 

從開放式構(gòu)造類型繼承的泛型類必須指定約束,這些約束是基類型約束的超集或暗示基類型約束:

class NodeItem<T> where T : System.IComparable<T>, new() { }class SpecialNodeItem<T> : NodeItem<T> where T : System.IComparable<T>, new() { }

泛型類型可以使用多個(gè)類型參數(shù)和約束,如下所示:

class SuperKeyType<K, V, U>  where U : System.IComparable<U>  where V : new(){ }

開放式構(gòu)造類型和封閉式構(gòu)造類型可以用作方法參數(shù):

void Swap<T>(List<T> list1, List<T> list2){  //code to swap items}void Swap(List<int> list1, List<int> list2){  //code to swap items}

如果某個(gè)泛型類實(shí)現(xiàn)了接口,則可以將該類的所有實(shí)例強(qiáng)制轉(zhuǎn)換為該接口。
泛型類是不變的。也就是說,如果輸入?yún)?shù)指定 List<BaseClass>,則當(dāng)您嘗試提供 List<DerivedClass> 時(shí),將會(huì)發(fā)生編譯時(shí)錯(cuò)誤。


泛型接口
為泛型集合類或表示集合中項(xiàng)的泛型類定義接口通常很有用。對(duì)于泛型類,使用泛型接口十分可取,例如使用 IComparable<T> 而不使用 IComparable,這樣可以避免值類型的裝箱和取消裝箱操作。.NET Framework 類庫(kù)定義了若干泛型接口,以用于 System.Collections.Generic 命名空間中的集合類。
將接口指定為類型參數(shù)的約束時(shí),只能使用實(shí)現(xiàn)此接口的類型。下面的代碼示例顯示從 SortedList<T> 類派生的 GenericList<T> 類。
 SortedList<T> 添加約束 where T : IComparable<T>。這將使 SortedList<T> 中的 BubbleSort 方法能夠?qū)α斜碓厥褂梅盒?CompareTo 方法。在此示例中,列表元素為簡(jiǎn)單類,即實(shí)現(xiàn) Person 的 IComparable<Person>。

//Type parameter T in angle brackets.public class GenericList<T> : System.Collections.Generic.IEnumerable<T>{  protected Node head;  protected Node current = null;  // Nested class is also generic on T  protected class Node  {    public Node next;    private T data; //T as private member datatype    public Node(T t) //T used in non-generic constructor    {      next = null;      data = t;    }    public Node Next    {      get { return next; }      set { next = value; }    }    public T Data //T as return type of property    {      get { return data; }      set { data = value; }    }  }  public GenericList() //constructor  {    head = null;  }  public void AddHead(T t) //T as method parameter type  {    Node n = new Node(t);    n.Next = head;    head = n;  }  // Implementation of the iterator  public System.Collections.Generic.IEnumerator<T> GetEnumerator()  {    Node current = head;    while (current != null)    {      yield return current.Data;      current = current.Next;    }  }  // IEnumerable<T> inherits from IEnumerable, therefore this class   // must implement both the generic and non-generic versions of   // GetEnumerator. In most cases, the non-generic method can   // simply call the generic method.  System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()  {    return GetEnumerator();  }}public class SortedList<T> : GenericList<T> where T : System.IComparable<T>{  // A simple, unoptimized sort algorithm that   // orders list elements from lowest to highest:  public void BubbleSort()  {    if (null == head || null == head.Next)    {      return;    }    bool swapped;    do    {      Node previous = null;      Node current = head;      swapped = false;      while (current.next != null)      {        // Because we need to call this method, the SortedList        // class is constrained on IEnumerable<T>        if (current.Data.CompareTo(current.next.Data) > 0)        {          Node tmp = current.next;          current.next = current.next.next;          tmp.next = current;          if (previous == null)          {            head = tmp;          }          else          {            previous.next = tmp;          }          previous = tmp;          swapped = true;        }        else        {          previous = current;          current = current.next;        }      }    } while (swapped);  }}// A simple class that implements IComparable<T> using itself as the // type argument. This is a common design pattern in objects that // are stored in generic lists.public class Person : System.IComparable<Person>{  string name;  int age;  public Person(string s, int i)  {    name = s;    age = i;  }  // This will cause list elements to be sorted on age values.  public int CompareTo(Person p)  {    return age - p.age;  }  public override string ToString()  {    return name + ":" + age;  }  // Must implement Equals.  public bool Equals(Person p)  {    return (this.age == p.age);  }}class Program{  static void Main()  {    //Declare and instantiate a new generic SortedList class.    //Person is the type argument.    SortedList<Person> list = new SortedList<Person>();    //Create name and age values to initialize Person objects.    string[] names = new string[]     {       "Franscoise",       "Bill",       "Li",       "Sandra",       "Gunnar",       "Alok",       "Hiroyuki",       "Maria",       "Alessandro",       "Raul"     };    int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 };    //Populate the list.    for (int x = 0; x < 10; x++)    {      list.AddHead(new Person(names[x], ages[x]));    }    //Print out unsorted list.    foreach (Person p in list)    {      System.Console.WriteLine(p.ToString());    }    System.Console.WriteLine("Done with unsorted list");    //Sort the list.    list.BubbleSort();    //Print out sorted list.    foreach (Person p in list)    {      System.Console.WriteLine(p.ToString());    }    System.Console.WriteLine("Done with sorted list");  }}

可將多重接口指定為單個(gè)類型上的約束,如下所示:

class Stack<T> where T : System.IComparable<T>, IEnumerable<T>{}

一個(gè)接口可定義多個(gè)類型參數(shù),如下所示:

interface IDictionary<K, V>{}

適用于類的繼承規(guī)則同樣適用于接口:

interface IMonth<T> { }interface IJanuary   : IMonth<int> { } //No errorinterface IFebruary<T> : IMonth<int> { } //No errorinterface IMarch<T>  : IMonth<T> { }  //No error//interface IApril<T> : IMonth<T, U> {} //Error

如果泛型接口為逆變的,即僅使用其類型參數(shù)作為返回值,則此泛型接口可以從非泛型接口繼承。在 .NET Framework 類庫(kù)中,IEnumerable<T> 從 IEnumerable 繼承,因?yàn)?IEnumerable<T> 只在 GetEnumerator 的返回值和 Current 屬性 getter 中使用 T。
具體類可以實(shí)現(xiàn)已關(guān)閉的構(gòu)造接口,如下所示:

interface IBaseInterface<T> { }class SampleClass : IBaseInterface<string> { }


只要類參數(shù)列表提供了接口必需的所有參數(shù),泛型類便可以實(shí)現(xiàn)泛型接口或已關(guān)閉的構(gòu)造接口,如下所示:

interface IBaseInterface1<T> { }interface IBaseInterface2<T, U> { }class SampleClass1<T> : IBaseInterface1<T> { }     //No errorclass SampleClass2<T> : IBaseInterface2<T, string> { } //No error

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 全州县| 长春市| 句容市| 沾益县| 石家庄市| 嫩江县| 铜陵市| 富宁县| 庆安县| 韶关市| 股票| 双城市| 周宁县| 衡南县| 锦屏县| 伊宁县| 江达县| 成武县| 永福县| 新乐市| 六盘水市| 无为县| 石景山区| 吴旗县| 象山县| 都江堰市| 和顺县| 怀远县| 桂林市| 灵丘县| 法库县| 昆山市| 白沙| 会宁县| 迭部县| 永福县| 临沧市| 临沧市| 宣汉县| 漾濞| 巴林右旗|