一个简单的例子学习c#泛型

using  System;
// 我们在编写程序时,经常遇到两个模块的功能非常相似,只是一个是处理int数据,另一个是处理string数据,或者其他自定义的数据类型,但我们没有办法,只能分别写多个方法处理每个数据类型,因为方法的参数类型不同。有没有一种办法,在方法中传入通用的数据类型,这样不就可以合并代码了吗?泛型的出现就是专门解决这个问题的。
namespace  Generic
{
    
class  Program
    {
        
static   void  Main( string [] args)
        {
            
// 一个普通的类,只能传入int类型的参数。
            print p  =   new  print( 5 );
            
// 使用了泛型,只需要在 < > 中定义参数类型就可以了。
            print1 < int >  p1  =   new  print1 < int > ( 5 );
            print1
< string >  p2  =   new  print1 < string > ( " p2 " );
            
// 泛型参数的约束,第一个必须是值类型(struct),第二个是引用类型(class)。
            print2 < int string >  p3  =   new  print2 < int string > ( 5 " p3 " );
            
// 泛型方法,可以对方法传入不同类型的参数。
            print3 p4  =   new  print3();
            p4.print(
" aaa " " bbb " " ccc " );
            p4.print(
111 , 222 , 333 );

            Console.ReadLine();
            
// 输出结果
            
// 5
            
// 5
            
// p2
            
// 5 p3
            
// aaa
            
// bbb
            
// ccc
            
// 111
            
// 222
            
// 333
        }
    }

    
class  print
    {
        
public  print( int  i)
        {
            Console.WriteLine(i);
        }
    }

    
class  print1 < T >
    {
        
public  print1(T t)
        {
            Console.WriteLine(t);
        }
    }
    
// 泛型约束,使用了where关键字。
     class  print2 < T, V >   where  T: struct   where  V: class
    {
        
public  print2(T t,V v)
        {
            Console.WriteLine(t 
+   "   "   +  v);
        }
    }

    
class  print3
    {
        
public  print3(){}
        
public   void  print < T > ( params  T[] p)
        {
            
foreach  (T t  in  p)
            {
                Console.WriteLine(t);
            }
        }
    }
}

转载于:https://www.cnblogs.com/spku400/archive/2009/07/26/1531527.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值