C#-泛型

一:介绍泛型

​ 泛型是程序设计语言的一种特性。允许程序员在强类型程序设计语言中编写代码时定义一些可变部分,那些部分在使用前必须作出指明。各种程序设计语言和其编译器、运行环境对泛型的支持均不一样。将类型参数化以达到代码复用提高软件开发工作效率的一种数据类型。泛型类是引用类型,是堆对象,主要是引入了类型参数这个概念。C#2.0之后出现泛型。

二:实例讲解

1.Object类型是一切类型的父类

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

1
2
3
4
public static void ShowObject(object obj)
{
Console.WriteLine("This is {0},parameter={1},type={2}", typeof(ComonMethed), obj.GetType().Name, obj);
}

泛型:使用一个方法,满足不同参数类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
   static void Main(string[] args)
{
object a = "123";
int i = 5;
string j = "6";
bool flag = true;
ComonMethed.Show<int>(i);
ComonMethed.Show<string>(j);
ComonMethed.Show<bool>(flag);
}
public class ComonMethed
{

public static void Show<T>(T obj)
{
Console.WriteLine("This is {0},parameter={1},type={2}", typeof(ComonMethed), obj.GetType().Name, obj.ToString());
}
}

1574910783041