namespace 数据结构
{
class Program
{
static void Main(string[] args)
{
int num1 = 10;
int num2 = 20;
Swap<int>(num1, num2);
// Console.WriteLine(num1 + " "+ num2);
Test<int,float> test = new Test<int,float>();
//int>(10, 20);
}
//泛型:泛型函数,泛型类
//泛型函数在调用的时候必须给定一个具体的数据类型
//对于某些函数在定义时,无法直接得知要使用的参数的数据类型,只能等调用的时候才能确定,可以使用泛型
//我们需要自定义一个数据类型,用这种数据类型来泛指其他的数据类型,那么自定义的这个数据类型叫泛型
//new(): 约束泛型类性必须具有公共的无参构造函数
//泛型约束之间是否存在书写顺序
//1、new 约束必须放在所有的约束之后
//2、struct 和 class约束必须放在所有的泛型约束之前
//泛型约束之间是否存在冲突
//1、class和struct约束不能和类的继承约束同时出现
//2、class和struct本身不能同时出现
//3、struct和new约束不能同时出现
static void Swap<T>(T num1, T num2)
{
T temp = num1;
num1 = num2;
num2 = temp;
}
//泛型约束
//泛型约束为值类型 where T : struct (c#中所有的值类型都是使用结构体封装的)
//泛型约束为引用类型 where T : class
//约束继承关系 where T : (类名,接口名) 强制要求只能是这个类型或者他们的子类可以使用
static T Sum<T>(T num1, T num2) where T : Base ,new()
{
return num1;
}
}
//在类名的后面加上<T>的形式的类型称为泛型类
//泛型类中字段和方法,如果需要使用泛型,可以不用额外的定义泛型
//多个泛型的问题
//c#中允许存在多个泛型,但在调用时必须给所有的泛型一个数据类型
class Test<T,V>
{
T test1;
T test2;
int test3;
V test4;
//泛型类中的函数,包括构造函数,在定义时都不需要再额外的写出泛型
//泛型类中可以包含其他的泛型函数,但是构造函数不能加泛型
public Test()
{
}
public void DoTest(T test1)
{
}
}
class Base
{
}
class Son : Base
{
}
}