本文實(shí)例分析了C#泛型用法。分享給大家供大家參考。具體分析如下:
這里演示如何創(chuàng)建具有單個(gè)類型參數(shù)的自定義泛型列表類,以及如何實(shí)現(xiàn) IEnumerable<T> 以便對列表的內(nèi)容啟用 foreach 迭代。此示例還演示客戶端代碼如何通過指定類型參數(shù)來創(chuàng)建該類的實(shí)例,以及該類型參數(shù)的約束如何實(shí)現(xiàn)對類型參數(shù)執(zhí)行其他操作。
using System;using System.Collections;using System.Collections.Generic;using System.Text;namespace Generics_CSharp{  // 尖括號中的類型參數(shù) T。  public class MyList<T> : IEnumerable<T>  {    protected Node head;    protected Node current = null;    // 嵌套類型也是 T 上的泛型    protected class Node    {      public Node next;      // T 作為私有成員數(shù)據(jù)類型。      private T data;      // 在非泛型構(gòu)造函數(shù)中使用的 T。      public Node(T t)      {        next = null;        data = t;      }      public Node Next      {        get { return next; }        set { next = value; }      }      // T 作為屬性的返回類型。      public T Data      {        get { return data; }        set { data = value; }      }    }    public MyList()    {      head = null;    }    // T 作為方法參數(shù)類型。    public void AddHead(T t)    {      Node n = new Node(t);      n.Next = head;      head = n;    }    // 實(shí)現(xiàn) GetEnumerator 以返回 IEnumerator<T>,從而啟用列表的    // foreach 迭代。請注意,在 C# 2.0 中,     // 不需要實(shí)現(xiàn) Current 和 MoveNext。    // 編譯器將創(chuàng)建實(shí)現(xiàn) IEnumerator<T> 的類。    public IEnumerator<T> GetEnumerator()    {      Node current = head;      while (current != null)      {        yield return current.Data;        current = current.Next;      }    }    // 必須實(shí)現(xiàn)此方法,因?yàn)?   // IEnumerable<T> 繼承 IEnumerable    IEnumerator IEnumerable.GetEnumerator()    {      return GetEnumerator();    }  }  public class SortedList<T> : MyList<T> where T : IComparable<T>  {    // 一個(gè)未優(yōu)化的簡單排序算法,    // 該算法從低到高對列表元素排序:    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)        {          // 由于需要調(diào)用此方法,因此,SortedList          // 類在 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;          }        }// end while      } while (swapped);    }  }  // 一個(gè)將自身作為類型參數(shù)來實(shí)現(xiàn) IComparable<T> 的簡單類,  // 是對象中的  // 常用設(shè)計(jì)模式,這些對象  // 存儲在泛型列表中。  public class Person : IComparable<Person>  {    string name;    int age;    public Person(string s, int i)    {      name = s;      age = i;    }    // 這會使列表元素    // 按 age 值排序。    public int CompareTo(Person p)    {      return age - p.age;    }    public override string ToString()    {      return name + ":" + age;    }    // 必須實(shí)現(xiàn) Equals。    public bool Equals(Person p)    {      return (this.age == p.age);    }  }  class Generics  {    static void Main(string[] args)    {      // 聲明并實(shí)例化一個(gè)新的范型 SortedList 類。      // Person 是類型參數(shù)。      SortedList<Person> list = new SortedList<Person>();      // 創(chuàng)建 name 和 age 值以初始化 Person 對象。      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 };      // 填充列表。      for (int x = 0; x < names.Length; x++)      {        list.AddHead(new Person(names[x], ages[x]));      }      Console.WriteLine("Unsorted List:");      // 打印出未排序的列表。      foreach (Person p in list)      {        Console.WriteLine(p.ToString());      }      // 對列表進(jìn)行排序。      list.BubbleSort();      Console.WriteLine(String.Format("{0}Sorted List:", Environment.NewLine));      // 打印出排序的列表。      foreach (Person p in list)      {        Console.WriteLine(p.ToString());      }      Console.WriteLine("Done");    }  }}希望本文所述對大家的C#程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選