C# 泛型

什么是泛型

泛型是C#2.0提出的类型参数化的功能

泛型的好处

  • 避免装箱拆箱,提高性能
  • 定义允许使用的数据类型,在编译时检查类型错误,及早发现错误

泛型的约束

使实参必须满足一定的规范,C#编译器在编译的过程中可以根据约束来检查所有泛型类型的实参并确保其满足约束条件

主要约束

一个泛型可以指定0或1个主要约束,主要约束可以一个非密封的引用类型,它表示类型实参必须与约束类型相同或者为约束类型的派生类。该引用类型不能为Object, Array, Delegate,Multicast Delegate, Value Type, Enum, Void

struct

限定当前参数类型必须是值类型

 class Person<T> where T:struct
{

}

class

限定当前类型参数类型必须是引用类型

 class Person<T> where T:class
{

}

new ()

限定当前参数类型必须有一个无参构造器

class Person<T> where T:new()
{

}

base class name

限定当前参数类型 必须是当前类 或者当前类为基类的类

class Student<T> where T : Person
{

}

次要约束

一个泛型可以拥有N个次要约束,次要约束规定了实参必须实现的所有的次要约束中规定的接口

interface name

限定当前参数类型必须实现指定接口

class Person<T> where T : IComparable
{

}

泛型的简单使用

泛型类

class Person<T>
{
    private T t;
    public Person(T p)
    {
        t = p;
    }
    public void ShowPerson()
    {
        Console.WriteLine(t);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person<int> person1 = new Person<int>(1);
        person1.ShowPerson();
        Person<string> person2 = new Person<string>("zhangsan");
        person2.ShowPerson();
    }
}

泛型方法

class Program
{
    static void Main(string[] args)
    {
        Sum<int>(1,2);
        Sum<double>(1.2, 1.3);
    }
    private static void Sum<T>(T a, T b) where T : struct
    {
        double sum = double.Parse(a.ToString()) + double.Parse(b.ToString());
        Console.WriteLine(sum);
    }
}

泛型接口

class Person : IFieldType<int>
{
    public void PrintType(int t)
    {
        Console.WriteLine(t.GetType());
    }
}
public interface IFieldType<T>
{
    void PrintType(T t);
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.PrintType(123);
    }
}

泛型委托

class Person<T> 
{
    public void Print(T s)
    {
        Console.WriteLine(s);
    }
    public void PrintType(T a)
    {
        Console.WriteLine(a.GetType());
    }
}


delegate void MyDel<T>(T param);

class Program
{
    static void Main(string[] args)
    {
        Person<string> person = new Person<string>();
        MyDel<string> myDel = new MyDel<string>(person.Print);
        myDel += person.PrintType;
        myDel("张三");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值