c# 泛型

c# 泛型


泛型是c#中一种代码重用技术。比如说两个模块功能相近,只是处理对象不同,一个是int,一个是float,这时使用通用参数可简化编程。
泛型与C++中模板机制类似,但没有模板复杂。比如c#不允许非类型模板参数:template  <int i>{};

//泛型
using System;
using System.Collections;//ArrayList所在类库
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    public class Point
    
    
     
     
    {
        public T x, y;
        public Point(T a,T b){
            x = a; y = b;
        }
        public void show()
        {
            Console.Write("{0}  {1}\n", x, y);
        }
    }
    class Program
    {
        
        static void Main(string[] args)
        {
            Point
     
     
      
       int_obj = new Point
      
      
       
       (3,4);
            Point
       
       
        
         str_obj = new Point
        
        
          ("hi","hello"); int_obj.show(); str_obj.show(); Console.Read(); } } } /* 输出; * 3 4 * hi hello */ 
        
       
       
      
      
     
     
    
    


c#还提供类型参数约束。

类型参数 T 约束
约束 说明
where T:struct 必须为值类型
shere T:class 必须为引用类型
shere T:new() 类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new()约束必须放最末
shere T:base_class_name 必须是此类或其派生类
shere T:interface_name 必须是此接口





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值