欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解C#中的泛型以及编程中使用泛型的优点

程序员文章站 2023-09-07 19:41:35
2.0 版 c# 语言和公共语言运行时 (clr) 中增加了泛型。泛型将类型参数的概念引入 .net framework,类型参数使得设计如下类和方法成为可能:这些类和方法...

2.0 版 c# 语言和公共语言运行时 (clr) 中增加了泛型。泛型将类型参数的概念引入 .net framework,类型参数使得设计如下类和方法成为可能:这些类和方法将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。例如,通过使用泛型类型参数 t,您可以编写其他客户端代码能够使用的单个类,而不致引入运行时强制转换或装箱操作的成本或风险,如下所示:

// declare the generic class.
public class genericlist<t>
{
  void add(t input) { }
}
class testgenericlist
{
  private class exampleclass { }
  static void main()
  {
    // declare a list of type int.
    genericlist<int> list1 = new genericlist<int>();

    // declare a list of type string.
    genericlist<string> list2 = new genericlist<string>();

    // declare a list of type exampleclass.
    genericlist<exampleclass> list3 = new genericlist<exampleclass>();
  }
}

泛型概述
使用泛型类型可以最大限度地重用代码、保护类型的安全以及提高性能。
泛型最常见的用途是创建集合类。
.net framework 类库在 system.collections.generic 命名空间中包含几个新的泛型集合类。应尽可能地使用这些类来代替普通的类,如 system.collections 命名空间中的 arraylist。
您可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。
可以对泛型类进行约束以访问特定数据类型的方法。
关于泛型数据类型中使用的类型的信息可在运行时通过使用反射获取。

泛型类和泛型方法同时具备可重用性、类型安全和效率,这是非泛型类和非泛型方法无法具备的。泛型通常用与集合以及作用于集合的方法一起使用。.net framework 2.0 版类库提供一个新的命名空间 system.collections.generic,其中包含几个新的基于泛型的集合类。建议面向 .net framework 2.0 及更高版本的所有应用程序都使用新的泛型集合类,而不要使用旧的非泛型集合类如 arraylist。

当然,也可以创建自定义泛型类型和方法,以提供自己的通用解决方案,设计类型安全的高效模式。下面的代码示例演示一个用于演示用途的简单泛型链接列表类。(大多数情况下,应使用 .net framework 类库提供的 list<t> 类,而不是自行创建类。)在通常使用具体类型来指示列表中存储的项的类型的场合,可使用类型参数 t。其使用方法如下:
在 addhead 方法中作为方法参数的类型。
在 node 嵌套类中作为公共方法 getnext 和 data 属性的返回类型。
在嵌套类中作为私有成员数据的类型。
注意,t 可用于 node 嵌套类。如果使用具体类型实例化 genericlist<t>(例如,作为 genericlist<int>),则所有的 t 都将被替换为 int。

// type parameter t in angle brackets
public class genericlist<t> 
{
  // the nested class is also generic on t.
  private class node
  {
    // t used in non-generic constructor.
    public node(t t)
    {
      next = null;
      data = t;
    }

    private node next;
    public node next
    {
      get { return next; }
      set { next = value; }
    }

    // t as private member data type.
    private t data;

    // t as return type of property.
    public t data 
    {
      get { return data; }
      set { data = value; }
    }
  }

  private node head;

  // constructor
  public genericlist() 
  {
    head = null;
  }

  // t as method parameter type:
  public void addhead(t t) 
  {
    node n = new node(t);
    n.next = head;
    head = n;
  }

  public ienumerator<t> getenumerator()
  {
    node current = head;

    while (current != null)
    {
      yield return current.data;
      current = current.next;
    }
  }
}

下面的代码示例演示客户端代码如何使用泛型 genericlist<t> 类来创建整数列表。只需更改类型参数,即可方便地修改下面的代码示例,创建字符串或任何其他自定义类型的列表:

class testgenericlist
{
  static void main()
  {
    // int is the type argument
    genericlist<int> list = new genericlist<int>();

    for (int x = 0; x < 10; x++)
    {
      list.addhead(x);
    }

    foreach (int i in list)
    {
      system.console.write(i + " ");
    }
    system.console.writeline("\ndone");
  }
}

泛型的优点
在公共语言运行时和 c# 语言的早期版本中,通用化是通过在类型与通用基类型 object 之间进行强制转换来实现的,泛型提供了针对这种限制的解决方案。通过创建泛型类,您可以创建一个在编译时类型安全的集合。
使用非泛型集合类的限制可以通过编写一小段程序来演示,该程序使用 .net framework 类库中的 arraylist 集合类。 arraylist 是一个使用起来非常方便的集合类,无需进行修改即可用来存储任何引用或值类型。

// the .net framework 1.1 way to create a list:
system.collections.arraylist list1 = new system.collections.arraylist();
list1.add(3);
list1.add(105);

system.collections.arraylist list2 = new system.collections.arraylist();
list2.add("it is raining in redmond.");
list2.add("it is snowing in the mountains.");

但这种方便是需要付出代价的。添加到 arraylist 中的任何引用或值类型都将隐式地向上强制转换为 object。如果项是值类型,则必须在将其添加到列表中时进行装箱操作,在检索时进行取消装箱操作。强制转换以及装箱和取消装箱操作都会降低性能;在必须对大型集合进行循环访问的情况下,装箱和取消装箱的影响非常明显。
另一个限制是缺少编译时类型检查;因为 arraylist 会将所有项都强制转换为 object,所以在编译时无法防止客户端代码执行类似如下的操作:

system.collections.arraylist list = new system.collections.arraylist();
// add an integer to the list.
list.add(3);
// add a string to the list. this will compile, but may cause an error later.
list.add("it is raining in redmond.");

int t = 0;
// this causes an invalidcastexception to be returned.
foreach (int x in list)
{
  t += x;
}

尽管将字符串和 ints 组合在一个 arraylist 中的做法在创建异类集合时是完全可接受的,并且有时需要有意为之,但这种做法很可能产生编程错误,并且直到运行时才能检测到此错误。
在 c# 语言的 1.0 和 1.1 版本中,只能通过编写自己的特定于类型的集合来避免 .net framework 基类库集合类中的通用代码的危险。当然,由于此类不可对多个数据类型重用,因此将丧失通用化的优点,并且您必须对要存储的每个类型重新编写该类。
arraylist 和其他相似类真正需要的是:客户端代码基于每个实例指定这些类要使用的具体数据类型的方式。这样将不再需要向上强制转换为 t:system.object,同时,也使得编译器可以进行类型检查。换句话说,arraylist 需要一个类型参数。这正是泛型所能提供的。在 n:system.collections.generic 命名空间的泛型 list<t> 集合中,向集合添加项的操作类似于以下形式:

// the .net framework 2.0 way to create a list
list<int> list1 = new list<int>();

// no boxing, no casting:
list1.add(3);

// compile-time error:
// list1.add("it is raining in redmond.");

对于客户端代码,与 arraylist 相比,使用 list<t> 时添加的唯一语法是声明和实例化中的类型参数。虽然这种方式稍微增加了编码的复杂性,但好处是您可以创建一个比 arraylist 更安全并且速度更快的列表,对于列表项是值类型的情况尤为如此。