欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#泛型详解

程序员文章站 2023-10-16 23:41:12
这篇文章主要讲解C#中的泛型,泛型在C#中有很重要的地位,尤其是在搭建项目框架的时候。 一、什么是泛型 泛型是C#2.0推出的新语法,不是语法糖,而是2.0由框架升级提供的功能。 我们在编程程序时,经常会遇到功能非常相似的模块,只是它们处理的数据不一样。但我们没有办法,只能分别写多个方法来处理不同的 ......

这篇文章主要讲解c#中的泛型,泛型在c#中有很重要的地位,尤其是在搭建项目框架的时候。

一、什么是泛型

泛型是c#2.0推出的新语法,不是语法糖,而是2.0由框架升级提供的功能。

我们在编程程序时,经常会遇到功能非常相似的模块,只是它们处理的数据不一样。但我们没有办法,只能分别写多个方法来处理不同的数据类型。这个时候,那么问题来了,有没有一种办法,用同一个方法来处理传入不同种类型参数的办法呢?泛型的出现就是专门来解决这个问题的。

二、为什么使用泛型

先来看下面一个例子:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
public class commonmethod
{
/// <summary>
/// 打印个int值
///
/// 因为方法声明的时候,写死了参数类型
/// 已婚的男人 eleven san
/// </summary>
/// <param name="iparameter"></param>
public static void showint(int iparameter)
{
console.writeline("this is {0},parameter={1},type={2}",
typeof(commonmethod).name, iparameter.gettype().name, iparameter);
}

/// <summary>
/// 打印个string值
/// </summary>
/// <param name="sparameter"></param>
public static void showstring(string sparameter)
{
console.writeline("this is {0},parameter={1},type={2}",
typeof(commonmethod).name, sparameter.gettype().name, sparameter);
}

/// <summary>
/// 打印个datetime值
/// </summary>
/// <param name="oparameter"></param>
public static void showdatetime(datetime dtparameter)
{
console.writeline("this is {0},parameter={1},type={2}",
typeof(commonmethod).name, dtparameter.gettype().name, dtparameter);
}
}
}

结果:

C#泛型详解

从上面的结果中我们可以看出这三个方法,除了传入的参数不同外,其里面实现的功能都是一样的。在1.0版的时候,还没有泛型这个概念,那么怎么办呢。相信很多人会想到了oop三大特性之一的继承,我们知道,c#语言中,object是所有类型的基类,将上面的代码进行以下优化:

public static void showobject(object oparameter)
{
      console.writeline("this is {0},parameter={1},type={2}",
         typeof(commonmethod), oparameter.gettype().name, oparameter);
}

 结果:

C#泛型详解

从上面的结果中我们可以看出,使用object类型达到了我们的要求,解决了代码的可复用。可能有人会问定义的是object类型的,为什么可以传入int、string等类型呢?原因有二:

1、object类型是一切类型的父类。

2、通过继承,子类拥有父类的一切属性和行为,任何父类出现的地方,都可以用子类来代替。

但是上面object类型的方法又会带来另外一个问题:装箱和拆箱,会损耗程序的性能。

微软在c#2.0的时候推出了泛型,可以很好的解决上面的问题。

三、泛型类型参数

在泛型类型或方法定义中,类型参数是在其实例化泛型类型的一个变量时,客户端指定的特定类型的占位符。 泛型类( genericlist<t>)无法按原样使用,因为它不是真正的类型;它更像是类型的蓝图。 若要使用 genericlist<t>,客户端代码必须通过指定尖括号内的类型参数来声明并实例化构造类型。 此特定类的类型参数可以是编译器可识别的任何类型。 可创建任意数量的构造类型实例,其中每个使用不同的类型参数。

上面例子中的代码可以修改如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
public class genericmethod
{
/// <summary>
/// 泛型方法
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="tparameter"></param>
public static void show<t>(t tparameter)
{
console.writeline("this is {0},parameter={1},type={2}",
typeof(genericmethod), tparameter.gettype().name, tparameter.tostring());
}
}
}

调用:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
class program
{
static void main(string[] args)
{

int ivalue = 123;
string svalue = "456";
datetime dtvalue = datetime.now;

console.writeline("***********commonmethod***************");
commonmethod.showint(ivalue);
commonmethod.showstring(svalue);
commonmethod.showdatetime(dtvalue);
console.writeline("***********object***************");
commonmethod.showobject(ivalue);
commonmethod.showobject(svalue);
commonmethod.showobject(dtvalue);
console.writeline("***********generic***************");
genericmethod.show<int>(ivalue);
genericmethod.show<string>(svalue);
genericmethod.show<datetime>(dtvalue);
console.readkey();
}
}
}

显示结果:

C#泛型详解

为什么泛型可以解决上面的问题呢?

泛型是延迟声明的:即定义的时候没有指定具体的参数类型,把参数类型的声明推迟到了调用的时候才指定参数类型。 延迟思想在程序架构设计的时候很受欢迎。例如:分布式缓存队列、ef的延迟加载等等。

泛型究竟是如何工作的呢?

控制台程序最终会编译成一个exe程序,exe被点击的时候,会经过jit(即时编译器)的编译,最终生成二进制代码,才能被计算机执行。泛型加入到语法以后,vs自带的编译器又做了升级,升级之后编译时遇到泛型,会做特殊的处理:生成占位符。再次经过jit编译的时候,会把上面编译生成的占位符替换成具体的数据类型。请看下面一个例子:

1 console.writeline(typeof(list<>));
2 console.writeline(typeof(dictionary<,>));

 结果:

C#泛型详解

从上面的截图中可以看出:泛型在编译之后会生成占位符。

注意:占位符需要在英文输入法状态下才能输入,只需要按一次波浪线(数字1左边的键位)的键位即可,不需要按shift键。

1、泛型性能问题

请看一下的一个例子,比较普通方法、object参数类型的方法、泛型方法的性能。

添加一个monitor类,让三种方法执行同样的操作,比较用时长短:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
public class monitor
{
public static void show()
{
console.writeline("****************monitor******************");
{
int ivalue = 12345;
long commonsecond = 0;
long objectsecond = 0;
long genericsecond = 0;

{
stopwatch watch = new stopwatch();
watch.start();
for (int i = 0; i < 100000000; i++)
{
showint(ivalue);
}
watch.stop();
commonsecond = watch.elapsedmilliseconds;
}
{
stopwatch watch = new stopwatch();
watch.start();
for (int i = 0; i < 100000000; i++)
{
showobject(ivalue);
}
watch.stop();
objectsecond = watch.elapsedmilliseconds;
}
{
stopwatch watch = new stopwatch();
watch.start();
for (int i = 0; i < 100000000; i++)
{
show<int>(ivalue);
}
watch.stop();
genericsecond = watch.elapsedmilliseconds;
}
console.writeline("commonsecond={0},objectsecond={1},genericsecond={2}"
, commonsecond, objectsecond, genericsecond);
}
}

#region privatemethod
private static void showint(int iparameter)
{
//do nothing
}
private static void showobject(object oparameter)
{
//do nothing
}
private static void show<t>(t tparameter)
{
//do nothing
}
#endregion

}
}

main()方法调用:

1 monitor.show();

 结果:

C#泛型详解

从结果中可以看出:泛型方法的性能最高,其次是普通方法,object方法的性能最低。

四、泛型类

除了方法可以是泛型以外,类也可以是泛型的,例如:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
/// <summary>
/// 泛型类
/// </summary>
/// <typeparam name="t"></typeparam>
public class genericclass<t>
{
public t _t;
}
}

main()方法中调用:

// t是int类型
genericclass<int> genericint = new genericclass<int>();
genericint._t = 123;
// t是string类型
genericclass<string> genericstring = new genericclass<string>();
genericstring._t = "123";

除了可以有泛型类,也可以有泛型接口,例如:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
/// <summary>
/// 泛型接口
/// </summary>
public interface igenericinterface<t>
{
//泛型类型的返回值
t gett(t t);
}
}

也可以有泛型委托:

1 public delegate void sayhi<t>(t t);//泛型委托

 注意:

1、泛型在声明的时候可以不指定具体的类型,但是在使用的时候必须指定具体类型,例如:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
/// <summary>
/// 使用泛型的时候必须指定具体类型,
/// 这里的具体类型是int
/// </summary>
public class commonclass :genericclass<int>
{
}
}

如果子类也是泛型的,那么继承的时候可以不指定具体类型,例如:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
/// <summary>
/// 使用泛型的时候必须指定具体类型,
/// 这里的具体类型是int
/// </summary>
public class commonclass :genericclass<int>
{
}

/// <summary>
/// 子类也是泛型的,继承的时候可以不指定具体类型
/// </summary>
/// <typeparam name="t"></typeparam>
public class commonclasschild<t>:genericclass<t>
{

}
}

2、类实现泛型接口也是这种情况,例如:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
/// <summary>
/// 必须指定具体类型
/// </summary>
public class common : igenericinterface<string>
{
public string gett(string t)
{
throw new notimplementedexception();
}
}

/// <summary>
/// 可以不知道具体类型,但是子类也必须是泛型的
/// </summary>
/// <typeparam name="t"></typeparam>
public class commonchild<t> : igenericinterface<t>
{
public t gett(t t)
{
throw new notimplementedexception();
}
}
}

五、泛型约束

先来看看下面的一个例子:

定义一个people类,里面有属性和方法:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
public interface isports
{
void pingpang();
}

public interface iwork
{
void work();
}


public class people
{
public int id { get; set; }
public string name { get; set; }

public void hi()
{
console.writeline("hi");
}
}

public class chinese : people, isports, iwork
{
public void tradition()
{
console.writeline("仁义礼智信,温良恭俭让");
}
public void sayhi()
{
console.writeline("吃了么?");
}

public void pingpang()
{
console.writeline("打乒乓球...");
}

public void work()
{
throw new notimplementedexception();
}
}

public class hubei : chinese
{
public hubei(int version)
{ }

public string changjiang { get; set; }
public void majiang()
{
console.writeline("打麻将啦。。");
}
}


public class japanese : isports
{
public int id { get; set; }
public string name { get; set; }
public void hi()
{
console.writeline("hi");
}
public void pingpang()
{
console.writeline("打乒乓球...");
}
}
}

在main()方法里面实例化:

people people = new people()
{
id = 123,
name = "走自己的路"
};
chinese chinese = new chinese()
{
id = 234,
name = "晴天"
};
hubei hubei = new hubei(123)
{
id = 345,
name = "流年"
};
japanese japanese = new japanese()
{
id = 7654,
name = "werwer"
};

这时有一个需求:需要打印出id和name属性的值,将showobject()方法修改如下:

C#泛型详解

但是这样修改报错了:object类里面没有id和name属性,可能会有人说,强制类型转换一下就行了啊:

public static void showobject(object oparameter)
{
console.writeline("this is {0},parameter={1},type={2}",
typeof(commonmethod), oparameter.gettype().name, oparameter);

console.writeline($"{((people)oparameter).id}_{((people)oparameter).name}");
}

这样修改以后,代码不会报错了,这时我们在main()方法里面调用:

1 commonmethod.showobject(people);
2 commonmethod.showobject(chinese);
3 commonmethod.showobject(hubei);
4 commonmethod.showobject(japanese);

 结果:

C#泛型详解

可以看出程序报错了,因为japanese没有继承自people,这里类型转换的时候失败了。这样会造成类型不安全的问题。那么怎么解决类型不安全的问题呢?那就是使用泛型约束。

所谓的泛型约束,实际上就是约束的类型t。使t必须遵循一定的规则。比如t必须继承自某个类,或者t必须实现某个接口等等。那么怎么给泛型指定约束?其实也很简单,只需要where关键字,加上约束的条件。

泛型约束总共有五种。

约束 s说明
t:结构 类型参数必须是值类型
t:类 类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。
t:new() 类型参数必须具有无参数的公共构造函数。 当与其他约束一起使用时,new() 约束必须最后指定。
t:<基类名> 类型参数必须是指定的基类或派生自指定的基类。
t:<接口名称> 类型参数必须是指定的接口或实现指定的接口。 可以指定多个接口约束。 约束接口也可以是泛型的。

1、基类约束

上面打印的方法约束t类型必须是people类型。

/// <summary>
/// 基类约束:约束t必须是people类型或者是people的子类
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="tparameter"></param>
public static void show<t>(t tparameter) where t : people
{
console.writeline($"{tparameter.id}_{tparameter.name}");
tparameter.hi();
}

注意:

基类约束时,基类不能是密封类,即不能是sealed类。sealed类表示该类不能被继承,在这里用作约束就无任何意义,因为sealed类没有子类。

2、接口约束

/// <summary>
/// 接口约束
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static t get<t>(t t) where t : isports
{
t.pingpang();
return t;
}

3、引用类型约束 class

引用类型约束保证t一定是引用类型的。

/// <summary>
/// 引用类型约束
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static t get<t>(t t) where t : class
{
return t;
}

4、值类型约束  struct

值类型约束保证t一定是值类型的。

/// <summary>
/// 值类型类型约束
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static t get<t>(t t) where t : struct
{
return t;
}

5、无参数构造函数约束  new()

/// <summary>
/// new()约束
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static t get<t>(t t) where t : new()
{
return t;
}

泛型约束也可以同时约束多个,例如:

public static void show<t>(t tparameter)
where t : people, isports, iwork, new()
{
console.writeline($"{tparameter.id}_{tparameter.name}");
tparameter.hi();
tparameter.pingpang();
tparameter.work();
}

注意:有多个泛型约束时,new()约束一定是在最后。

六、泛型的协变和逆变

协变和逆变是在.net 4.0的时候出现的,只能放在接口或者委托的泛型参数前面,out 协变covariant,用来修饰返回值;in:逆变contravariant,用来修饰传入参数。

先看下面的一个例子:

定义一个animal类:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
public class animal
{
public int id { get; set; }
}
}

然后在定义一个cat类继承自animal类:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
public class cat :animal
{
public string name { get; set; }
}
}

在main()方法可以这样调用:

// 直接声明animal类
animal animal = new animal();
// 直接声明cat类
cat cat = new cat();
// 声明子类对象指向父类
animal animal2 = new cat();
// 声明animal类的集合
list<animal> listanimal = new list<animal>();
// 声明cat类的集合
list<cat> listcat = new list<cat>();

那么问题来了:下面的一句代码是不是正确的呢?

1 list<animal> list = new list<cat>();

 可能有人会认为是正确的:因为一只cat属于animal,那么一群cat也应该属于animal啊。但是实际上这样声明是错误的:因为list<cat>和list<animal>之间没有父子关系。

C#泛型详解

这时就可以用到协变和逆变了。

1 // 协变
2 ienumerable<animal> list1 = new list<animal>();
3 ienumerable<animal> list2 = new list<cat>();

 f12查看定义:

C#泛型详解

可以看到,在泛型接口的t前面有一个out关键字修饰,而且t只能是返回值类型,不能作为参数类型,这就是协变。使用了协变以后,左边声明的是基类,右边可以声明基类或者基类的子类。

协变除了可以用在接口上面,也可以用在委托上面:

1 func<animal> func = new func<cat>(() => null);

 除了使用.net框架定义好的以为,我们还可以自定义协变,例如:

/// <summary>
/// out 协变 只能是返回结果
/// </summary>
/// <typeparam name="t"></typeparam>
public interface icustomerlistout<out t>
{
t get();
}

public class customerlistout<t> : icustomerlistout<t>
{
public t get()
{
return default(t);
}
}

使用自定义的协变:

1 // 使用自定义协变
2 icustomerlistout<animal> customerlist1 = new customerlistout<animal>();
3 icustomerlistout<animal> customerlist2 = new customerlistout<cat>();

 在来看看逆变。

在泛型接口的t前面有一个in关键字修饰,而且t只能方法参数,不能作为返回值类型,这就是逆变。请看下面的自定义逆变:

/// <summary>
/// 逆变 只能是方法参数
/// </summary>
/// <typeparam name="t"></typeparam>
public interface icustomerlistin<in t>
{
void show(t t);
}

public class customerlistin<t> : icustomerlistin<t>
{
public void show(t t)
{
}
}

使用自定义逆变:

1 // 使用自定义逆变
2 icustomerlistin<cat> customerlistcat1 = new customerlistin<cat>();
3 icustomerlistin<cat> customerlistcat2 = new customerlistin<animal>();

协变和逆变也可以同时使用,看看下面的例子:

/// <summary>
/// int 逆变
/// outt 协变
/// </summary>
/// <typeparam name="int"></typeparam>
/// <typeparam name="outt"></typeparam>
public interface imylist<in int, out outt>
{
void show(int t);
outt get();
outt do(int t);
}

public class mylist<t1, t2> : imylist<t1, t2>
{

public void show(t1 t)
{
console.writeline(t.gettype().name);
}

public t2 get()
{
console.writeline(typeof(t2).name);
return default(t2);
}

public t2 do(t1 t)
{
console.writeline(t.gettype().name);
console.writeline(typeof(t2).name);
return default(t2);
}
}

使用:

1 imylist<cat, animal> mylist1 = new mylist<cat, animal>();
2 imylist<cat, animal> mylist2 = new mylist<cat, cat>();//协变
3 imylist<cat, animal> mylist3 = new mylist<animal, animal>();//逆变
4 imylist<cat, animal> mylist4 = new mylist<animal, cat>();//逆变+协变

 七、泛型缓存

在前面我们学习过,类中的静态类型无论实例化多少次,在内存中只会有一个。静态构造函数只会执行一次。在泛型类中,t类型不同,每个不同的t类型,都会产生一个不同的副本,所以会产生不同的静态属性、不同的静态构造函数,请看下面的例子:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace mygeneric
{
public class genericcache<t>
{
static genericcache()
{
console.writeline("this is genericcache 静态构造函数");
_typetime = string.format("{0}_{1}", typeof(t).fullname, datetime.now.tostring("yyyymmddhhmmss.fff"));
}

private static string _typetime = "";

public static string getcache()
{
return _typetime;
}
}
}

然后新建一个测试类,用来测试genericcache类的执行顺序:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading;
using system.threading.tasks;

namespace mygeneric
{
public class genericcachetest
{
public static void show()
{
for (int i = 0; i < 5; i++)
{
console.writeline(genericcache<int>.getcache());
thread.sleep(10);
console.writeline(genericcache<long>.getcache());
thread.sleep(10);
console.writeline(genericcache<datetime>.getcache());
thread.sleep(10);
console.writeline(genericcache<string>.getcache());
thread.sleep(10);
console.writeline(genericcache<genericcachetest>.getcache());
thread.sleep(10);
}
}
}
}

main()方法里面调用:

1 genericcachetest.show();

结果:

C#泛型详解

从上面的截图中可以看出,泛型会为不同的类型都创建一个副本,所以静态构造函数会执行5次。 而且每次静态属性的值都是一样的。利用泛型的这一特性,可以实现缓存。

注意:只能为不同的类型缓存一次。泛型缓存比字典缓存效率高。泛型缓存不能主动释放