C#泛型

C#泛型有两种形式:

  1. 泛型方法
  2. 泛型类型(类、接口、委托和结构)

泛型方法能够进行类型推断,泛型类型不能。

泛型方法

class GenericTest
{
    public T Self<T>(T a)
    {
        return a;
    }
}
static void Main(string[] args)
{
    GenericTest tester = new GenericTest();
    //指定类型
    Console.WriteLine(tester.Self<int>(9));
    //类型推断
    Console.WriteLine(tester.Self(9.1F));

    Console.ReadKey();
}

泛型类型

class GenericTest<T>
{
    private T value;

    public GenericTest(T value)
    {
        this.value = value;
    }

    public T Get()
    {
        return value;
    }
}

类型约束

可以在定义泛型类型和泛型方法的时候指定类型约束,有4种约束。

引用类型约束

用于确保使用的类型实参是引用类型的,必须是类型参数指定的第一个约束

struct Bike<T> where T : class
{
    public void Load<K>(K goods) where K : class
    {

    }
}


class Car<T> where T : class
{
    public void Load<K>(K goods) where K : class
    {

    }
}

值类型约束

确保使用的类型实参是值类型

class Train<T> where T : struct
{
    public void Load<K>(K goods) where K : struct
    {

    }
}

构造函数类型约束

确保类型实参有一个可用于创建实例的无参构造函数,必须是类型参数的最后一个约束,所有值类型实参都满足约束。

class Airplane<T> where T : new()
{
    public void Load<K>(K goods) where K : new()
    {

    }
}

转换类型约束

确保类型实参可以隐式转换为指定的类型

class Ship<T> where T : Exception
{

}

// 可以指定多个接口,但只能指定一个类
class Boat<T> where T : Exception, ICollection<T>, IDisposable
{

}

组合约束

对4种约束的组合

class Tank<T> where T : class, IComparable, new()
{

}

不同的类型可以有不同的约束

class Misslie<T, K> where T : class where K : new()
{

}

 

posted @ 2019-02-26 23:42  aloog  阅读(135)  评论(0编辑  收藏  举报