泛型的理解

 泛型的理解可以总结下面的一句话,它是把数据类型作为一种参数传递进来。
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;
        }

    

    }

}


下边的这个应用是泛型的又一种用法
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  ConsoleApplication5
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            test
<testType> ti = new test<testType>(4);
            ti.foo();
            Console.WriteLine(ti.DataInt);

        }

    }

    
class test<T> where T : ITest, new()//new()的作用是能够把传递进的的参数类型实例子化
//在这个限制语句规定了在传递进来的参数类型要实现接口ITest
    {
        
public test(int i)
        
{
            dataT 
= new T();
//等同于 System.Activator.CreateInstance<T>();仍然是用反射机制来获取泛型对象的实例的。
            dataInt = i;
        }

        
public void foo()
        
{
            dataT.testMethod();
        }

        
public T DataT
        
{
            
get return dataT; }
        }

        
public int DataInt
        
{
            
get return dataInt; }
        }

        
private T dataT;
        
private int dataInt;
    }

    
interface ITest
    
{
        
void testMethod();
    }


    
class testType : ITest
    
{
        
public void testMethod()
        
{
            Console.WriteLine(
"testing");
        }

    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值