C# 泛型

1.什么是泛型?

是将不确定的类型预先定义下来的一种C#高级语法

2.主要有泛型类,泛型方法,泛型接口,泛型委托,以下举例说明:

泛型类:

public class Test<T> 
    {
        private List<T> list = new List<T>();
 
        public int Count => list.Count;
 
        public void Add(T t)
        {
            if(t != null)
                list.Add(t);
        }
    }

泛型方法:

public class Test
{
    public static int Add<T>(T x,T y)
    {
          return int.Parse(x.ToString()) + int.Parse(y.ToString());
    }
}

   public static void Main(string[] args)
    {
        int result = Test.Add("3", "4");
        Console.WriteLine(result);
 
        Console.ReadKey();
    }

泛型接口

public interface IFace<T>

{

void SayHi(T msg);

}

泛型委托

Action /Fun

泛型约束

public class MyClass1<T, K, V, W, X,Y>
        where T : struct        //约束 T 必须是值类型  
        where K : class         //约束 K 必须是引用类型   
        where V : IFace<T>      //约束 V 必须实现 IFace 接口  
        where W : K             //约束 W 必须是 K 类型,或者是 K 类型的子类  
        where X : class, new()  //约束 X 必须是引用类型,并且有一个无参数的构造函数,当有多个约束时,new()必须写在最后  
        where Y : MyClass2      //约束 Y 必须是 MyClass2 类型,或者继承于 MyClass2 类
    {
        public void Add(T num)
        {
            Console.WriteLine(num);
        }
    }
 
    public class MyClass2
    {
 
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值