什么是泛型编程思想?及其简单的应…

来源:互联网 发布:mac持久哑光液体唇膏 编辑:程序博客网 时间:2024/05/16 06:28

什么是泛型编程思想?泛型 :赋予了类型 参数式 多态 的能力
泛型的第一个好处是编译时的严格类型检查。这是集合框架最重要的特点。此外,泛型消除了绝大多数的类型转换。如果没有泛型,当你使用集合框架时,你不得不进行类型转换。


关于泛型的理解可以总结下面的一句话,它是把数据类型作为一种参数传递进来。下边的这段代码是泛型的一个最简单的应用
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
    classProgram
    {
       static void Main(string[] args)
       {
           *//string 类型和int类型都实现了IComparable接口
           CompareIt<int> com = newCompareIt<int>();
           
           int i = 5;
           int j = 10;
           com.Max(i, j);
           int iResult = com.Max(i, j);
           Console.WriteLine("The Max of {0} and {1} is: {2}", i, j,iResult);

           CompareIt<string > compare3=newCompareIt<string>();
           string s1="Lesson 1";
           string s2="Lesson 2";
           string d=compare3.Max(s1, s2);
           Console.WriteLine("The Max of {0} and {1} is: {2}", s1, s2 ,d);
       }
    }
    classCompareIt<ItemType> where ItemType :IComparable//where 是一个限制条件语句,规定了传进来的参数类型要实现了IComparable接口
    {
       public ItemType Max(ItemType item1, ItemType item2)
       {
           
           int iResult = item1.CompareTo(item2);
           if (iResult > 0)// item 1 is greater thanitem2
           {
               return item1;
           }
           else if (iResult < 0)// item2 is greater thanitem1
           {
               return item2;
           }
           return item2;
        
    }
}

本文来自: IT知道网(http://www.itwis.com) 详细出处参考:http://www.itwis.com/html/net/c/20080512/1479.html

0 0
原创粉丝点击