泛型

1.前言

  面向对象语言三大特性:封装,继承,多态

  object是所有类型的父类,任何父类出现的地方,都可以用子类来代替

  例如:

    函数定义如下:

public static void igetData(int t)
{
Console.WriteLine("data={0},,type={1}", t, t.GetType());

}
public static void sgetData(string t)
{
Console.WriteLine("data={0},,type={1}", t, t.GetType());

}
public static void pgetData(People t)
{
Console.WriteLine("data={0},,type={1}", t, t.GetType());

}
public static void ogetData(object t) //任何父类出现的地方,都可以用子类来代替,所有参数t可以是任何类型,既可以使用这一个函数实现上面三个函数的功能
{
Console.WriteLine("data={0},,type={1}", t, t.GetType());
}

执行代码:

People people = new People()
{
id = 1,
name = "kxy"
};
Common.igetData(3);//调用原本定义的函数
Common.sgetData("hello");
Common.pgetData(people);

Common.ogetData(3);//调用objec函数
Common.ogetData("hello");
Common.ogetData(people);

执行结果一样:

但是这种方法有一个装箱和拆箱的操作,对性能有一定的损失,所以我们引入泛型的概念。

2.泛型

  延迟制定类型,把类型的指定推迟到编译阶段,函数如下:

public static void tgetData<T>(T t)
{
Console.WriteLine("data={0},,type={1}" ,t,t.GetType());
}

执行代码:

Common.tgetData(3);
Common.tgetData("hello");
Common.tgetData(people);

结果也相同

也可以在调用函数时制定它的类型:

Common.tgetData<int>(3);
Common.tgetData<string>("hello");
Common.tgetData<People>(people);

泛型方法编译时根据调用函数生成该函数传值类型对应的原函数,所以说泛型只是一个语法糖,没有性能损失。

 3.泛型的返回

public static T GetT<T>(T t)
{
return t;

//return default(T); //根据T的类型,返回一个T的默认值;引用类型默认返回null,如string类型;值类型返回0(不一定全是),如int类型
}

4.泛型类

5.泛型接口

6.泛型委托

7.泛型的约束

public static T GetT<T>(T t) where T:class //约束泛型为引用类型
{
return default(T);
}

即参数无法使用int这种值类型

public static T Query<T>(T t) where T :struct //约束泛型为值类型
{
return default(T);
}

即参数无法使用string这种引用类型

public static T GetT<T>(T t) where T:class,new()//使引用类型可以new对象,当然该类型必须有构造函数才可以,即string这种无构造函数的会报错,可以传people参数
{
T tt = new T();
return tt;
}

public static void sayHello<T>(T t) where T:People //具体约束类型

原文地址:https://www.cnblogs.com/wskxy/p/9103552.html