您当前的位置: 首页 > 

[泛型]什么是泛型

发布时间:2010-11-21 22:55:00 ,浏览量:0

泛型:即通过参数化类型来实现在同一份代码上操作多种数据类型。泛型编程是一种编程范式,它利用“参数化类型”将类型抽象化,从而实现更为灵活的复用。

C#泛型的作用概述:

C#泛型赋予了代码更强的类型安全,更好的复用,更高的效率,更清晰的约束。

在一个方法中,一个变量的值是可以作为参数,但其实这个变量的类型本身也可以作为参数。泛型允许我们在调用的时候再指定这个类型参数是什么。在.net中,泛型能够给我们带来的两个明显的好处是--类型安全和减少装箱、拆箱。 下面我们先看一个例子,说明为什么要使用泛型。 using System; using System.Collections; public class Person { public Person(string Name, int Age) //构造函数 {    this.age = Age;    this.name = Name; } private string name; private int age; public string Name {    set    {     name = value;    }    get    {     return name;    } } public int Age {    set    {     age = value;    }    get    {     return age;    } } }

class Program { static void Main() {    ArrayList peoples = new ArrayList();    peoples.Add(new Person("李小龙", 17));    peoples.Add(new Person("成龙", 17));    peoples.Add("谁是功夫之王?");    foreach (Person p in peoples)    {     Console.WriteLine(p.Name + "今年" + p.Age + "岁");    } } }

//我们在程序的入口点处运行,在集合中增加了一个其他类型的对象,但插入数据的时候并没有报错,编译也可以通过,但把“谁是功夫之王?”这样的字段转换成人员的时候出问题了,这说明ArrayList是类型不安全的。

这根本原因在于ArrayList和HashTable集合把每个元素都当作Object类型,在添加元素时不做类型检查,进行了装箱操作,将所有的数据类型都转换为object类型。检索元素时,对存储元素进行拆箱才可以还原数据,如此频繁和进行装箱与拆箱,对系统的性能提出了更高的要求,同时每次都要进行强制类型转换也很麻烦,容易出错。为了解决这个问题,C#引入了泛型技术。

将上面的代码改为:

using System; using System.Collections; using System.Collections.Generic; public class Person { public Person(string Name, int Age) //构造函数 {    this.age = Age;    this.name = Name; } private string name; private int age; public string Name {    set    {     name = value;    }    get    {     return name;    } } public int Age {    set    {     age = value;    }    get    {     return age;    } } } class Program { static void Main(string[]args) {    List < Person > peoples = new List < Person > ();    peoples.Add(new Person("成龙", 18));    peoples.Add(new Person("李小龙", 17));    peoples.Add("谁是功夫之王?");    foreach (Person person in peoples)    {     Console.WriteLine(person.Name + "今年" + person.Age + "岁。");    } } }

这段代码会报错,去掉这一句peoples.Add("谁是功夫之王?");就会正常运行。

关注
打赏
1688896170
查看更多评论

暂无认证

  • 0浏览

    0关注

    106485博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.3760s