C#泛型用法实例分析

所属分类: 软件编程 / C#教程 阅读数: 84
收藏 0 赞 0 分享

本文实例分析了C#泛型用法。分享给大家供大家参考。具体分析如下:

这里演示如何创建具有单个类型参数的自定义泛型列表类,以及如何实现 IEnumerable<T> 以便对列表的内容启用 foreach 迭代。此示例还演示客户端代码如何通过指定类型参数来创建该类的实例,以及该类型参数的约束如何实现对类型参数执行其他操作。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Generics_CSharp
{
  // 尖括号中的类型参数 T。
  public class MyList<T> : IEnumerable<T>
  {
    protected Node head;
    protected Node current = null;
    // 嵌套类型也是 T 上的泛型
    protected class Node
    {
      public Node next;
      // T 作为私有成员数据类型。
      private T data;
      // 在非泛型构造函数中使用的 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 作为方法参数类型。
    public void AddHead(T t)
    {
      Node n = new Node(t);
      n.Next = head;
      head = n;
    }
    // 实现 GetEnumerator 以返回 IEnumerator<T>,从而启用列表的
    // foreach 迭代。请注意,在 C# 2.0 中, 
    // 不需要实现 Current 和 MoveNext。
    // 编译器将创建实现 IEnumerator<T> 的类。
    public IEnumerator<T> GetEnumerator()
    {
      Node current = head;
      while (current != null)
      {
        yield return current.Data;
        current = current.Next;
      }
    }
    // 必须实现此方法,因为
    // IEnumerable<T> 继承 IEnumerable
    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }
  public class SortedList<T> : MyList<T> where T : IComparable<T>
  {
    // 一个未优化的简单排序算法,
    // 该算法从低到高对列表元素排序:
    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)
        {
          // 由于需要调用此方法,因此,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);
    }
  }
  // 一个将自身作为类型参数来实现 IComparable<T> 的简单类,
  // 是对象中的
  // 常用设计模式,这些对象
  // 存储在泛型列表中。
  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;
    }
    // 必须实现 Equals。
    public bool Equals(Person p)
    {
      return (this.age == p.age);
    }
  }
  class Generics
  {
    static void Main(string[] args)
    {
      // 声明并实例化一个新的范型 SortedList 类。
      // Person 是类型参数。
      SortedList<Person> list = new SortedList<Person>();
      // 创建 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());
      }
      // 对列表进行排序。
      list.BubbleSort();
      Console.WriteLine(String.Format("{0}Sorted List:", Environment.NewLine));
      // 打印出排序的列表。
      foreach (Person p in list)
      {
        Console.WriteLine(p.ToString());
      }
      Console.WriteLine("Done");
    }
  }
}

希望本文所述对大家的C#程序设计有所帮助。

更多精彩内容其他人还在看

c#开发word批量转pdf源码分享

已经安装有Office环境,借助一些简单的代码即可实现批量Word转PDF,看下面的实例源码吧
收藏 0 赞 0 分享

c# xml API操作的小例子

这篇文章主要介绍了c# xml API操作的小例子,有需要的朋友可以参考一下
收藏 0 赞 0 分享

c#唯一值渲染实例代码

这篇文章主要介绍了c#唯一值渲染实例代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

淘宝IP地址库采集器c#代码

这篇文章主要介绍了淘宝IP地址库采集器c#代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C#在后台运行操作(BackgroundWorker用法)示例分享

BackgroundWorker类允许在单独的专用线程上运行操作。如果需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用BackgroundWorker类方便地解决问题,下面看示例
收藏 0 赞 0 分享

c#文本加密程序代码示例

这是一个加密软件,但只限于文本加密,加了窗口控件的滑动效果,详细看下面的代码
收藏 0 赞 0 分享

c#生成站点地图(SiteMapPath)文件示例程序

这篇文章主要介绍了c#生成站点地图(SiteMapPath)文件的示例,大家参考使用
收藏 0 赞 0 分享

C# 键盘Enter键取代Tab键实现代码

这篇文章主要介绍了C# 键盘Enter键取代Tab键实现代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C# WinForm导出Excel方法介绍

在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,本文只介绍前两种方式
收藏 0 赞 0 分享

C#串口通信程序实例详解

在.NET平台下创建C#串口通信程序,.NET 2.0提供了串口通信的功能,其命名空间是System.IO.Ports,创建C#串口通信程序的具体实现是如何的呢?让我们开始吧
收藏 0 赞 0 分享
查看更多