以下为自己的个人理解:
是把重复的类进行一个整合防止类型膨胀,成员膨胀。
在定义一个类,接口,方法等的时候不明确定义类型用 <类型参数> 来定义,等要使用的时候再去明确定义,这就是泛型。
类型参数是指一个泛化的类型,就是用一个标识符来表示,标识符是由自己命名,可以是ABD,DSD。
泛型有正交性,个人理解是有许多种泛型:泛型类,泛型接口,泛型委托,泛型方法等等
例子1 泛型类:
下面是一个商店里的包装,商店里的苹果和书本用盒子装起来,因为苹果和书长不一样,所以我要使用不同的盒子。
打个比方,苹果有不同颜色和牌子,有青苹果和红苹果,有富士山苹果等等,所以我要在苹果的盒子上写苹果的颜色(color)和牌子(brand),书有很多,每本书的作者也可能不一样,比如哈姆雷特是莎士比亚写的,悲惨世界是雨果写的,在书的盒子外面要写上作者(Author)和名字(Name)来区分。
于是就有了苹果盒子(AppleBox),书本盒子(BookBox),但是他们本质上都是盒子,那么我们可以先把盒子买来,但是先不决定它是什么盒子(假设这里的这个盒子贴上啥标签就会变成什么盒子),等要用盒子的时候,再给这个盒子贴上标签来确定是苹果盒子还是书本盒子。
我的苹果和书本分别是Apple和Book类型,把盒子定义为一个泛型类(Box),它的类型定义为,TCargo是我自己的定义的,表示货物类型,这个<>里面的标识符由自己定义,当我要使用盒子的时候,就把TCargo改为我要装进去的物品类型,比如是书本盒子就变成Box,以下是具体例子
static void Main(string[] args)
{
Apple apple = new Apple {
Color = "Red" ,Brand="富士山"};
Book book = new Book {
Name = "哈姆雷特" ,Author="莎士比亚"};
Box<Apple> box1 = new Box<Apple> {
Cargo = apple };
Box<Book> box2 = new Box<Book> {
Cargo = book };
Console.WriteLine("苹果颜色:{0},牌子:{1}", box1.Cargo.Color,box1.Cargo.Brand);
Console.WriteLine("书名:{0},作者:{1}",box2.Cargo.Name,box2.Cargo.Author);
}
class Apple
{
public string Color {
get; set; }
public string Brand {
get; set; }
}
class Book
{
public string Name {
get; set; }
public string Author {
get; set; }
}
class Box<TCargo>
{
public TCargo Cargo {
get; set; }
}
static void Main(string[] args)
{
Student<ulong> student = new Student<ulong> {
};
//使用接口时没有特化泛型接口
student.ID = 10000000000001;
student.Name = "莎士比亚";
//使用接口时特化泛型接口
Teacher teacher = new Teacher {
};
teacher.ID = 1000000000000001;
teacher.Name = "孔子";
}
interface IUnique<TId>
{
TId ID {
get; set; }
}
//使用接口时没有特化泛型接口
class Student<TId> : IUnique<TId>
{
public TId ID {
get; set; }
public string Name;
}
//使用接口时特化泛型接口
class Teacher : IUnique<ulong>
{
public ulong ID {
get; set; }
public string Name;
}
}
例子3 泛型方法
static void Main(string[] args)
{
int[] a1 = {
1, 3, 5, 7 };
int[] a2 = {
2, 4, 6, 8 };
double[] a3 = {
1.1, 3.3, 5.5, 7.7 };
double[] a4 = {
2.2, 4.4, 6.6, 8.8 };
var result = zip(a1, a2);
Console.WriteLine(string.Join(",", result));
}
static T[] zip<T>(T[] a, T[] b)
{
T[] zipped = new T[a.Length + b.Length];
int ai = 0, bi = 0, zi = 0;
do
{
if (ai < a.Length)
{
zipped[zi++] = a[ai++];
}
if (bi < b.Length)
{
zipped[zi++] = b[bi++];
}
} while (ai < a.Length || bi < b.Length);
return zipped;
}
小笔记
记一下,以后有问题再回来改,如果有错误也可以在评论区指出
有待补充…