您现在的位置: 无忧电子商务网 >> 信息学院 >> 程序开发 >> asp.net >> 正文

彻底剖析C# 2.0泛型类的创建和使用

作者:佚名    信息学院来源:整理    点击数:    更新时间:2008-1-30 我要参与讨论

  llections.Generic;
using System.Text;
namespace Generics{
 class Program{
  static void Main(string[] args){
   List<Customer> customers = new List<Customer>();
   customers.Add(new Customer("Motown-Jobs"));
   customers.Add(new Customer("Fatman's"));
   foreach (Customer c in customers)
   Console.WriteLine(c.CustomerName);
   Console.ReadLine();
  }
 }
 public class Customer{
  private string customerName = "";
  public string CustomerName{
   get { return customerName; }
   set { customerName = value; }
  }
  public Customer(string customerName){
   this.customerName = customerName;
  }
 }
}


  注意,我们有一个强类型集合-List<Customer>-对这个集合类本身来说不需要写一句代码。如果我们想要扩展列表customer,我们可以通过从List<Customer>继承而派生一个新类。

  三、 实现一个泛型类

  一种合理的实现某种新功能的方法是在原有的事物上进一步构建。我们已经了解强类型集合,并知道一种不错的用来构建泛型类的技术是使用一个特定类并删除数据类型。也就是说,让我们定义一个强类型集合CustomerList,并且来看一下它要把什么东西转化成一个泛型类。

  列表2定义了一个类CustomerList。后面的部分把CustomerList转化成List<T>。

  列表2定义类CustomerList:

using System;
using System.Collections;
using System.Text;
namespace Generics{
 public class CustomerList : CollectionBase{
  public CustomerList() { }
  public Customer this[int index]{
   get { return (Customer)List[index]; }
   set { List[index] = value; }
  }
  public int Add(Customer value)
  {return List.Add(value);}
 }
}


  四、 定义类头

  如果我们定义一个泛型类,我们需要把类头转化成一个泛型类。所有我们需要做的是命名参数并且把类名改成某种泛型。List<T>只有一个参数T,并且因为我们在以一种向后兼容的方式工作,所以我们知道类名是List。列表3显示出列表2中类的新类头。

  列表3 一个泛型类头显示出参数化

上一页  [1] [2] [3] [4] 下一页

在google里搜索更多彻底剖析C# 2.0泛型类的创建和使用

Google
Web www.51ec.org
  • 上一篇信息学院:

  • 下一篇信息学院:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
    我来说两句 对此文章发表了评论
      昵 称: *必填    ·注册用户·
      评 分: 1分 2分 3分 4分 5分     严禁发表危害国家安全、政治、黄色淫秽等内容的评论,用户需对自己在使用本网站服务过程中的行为承担法律责任。本站管理员有权保留或删除评论内容,评论内容只代表机友个人观点,与本网站立场无关。  
    评 论
    内 容

     
    评论列表 (最新 评论仅限网友观点!)

    供求信息




    | 设为首页 | 加入收藏 | 关于我们 | 广告服务 | 联系方式 | 友情链接 | 版权申明