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

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


关于泛型的理解可以总结下面的一句话,它是把数据类型作为一种参数传递进来。下边的这段代码是泛型的一个最简单的应用
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            *//string 类型和int类型都实现了IComparable接口
            CompareIt<int> com = new CompareIt<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=new CompareIt<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);
        }
    }
    class CompareIt<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 than item2
            {
                return item1;
            }
            else if (iResult < 0)// item2 is greater than item1
            {
                return item2;
            }
            return item2;
        
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值