C#学习记录-泛型

将不确定的类型预先定义下来。我们写的类、接口或方法中,相同的代码为不同的类型提供服务,就可以定义为泛型,可以简化我们的代码结构

示例代码:

1
2
3
4
5
6
7
8
//泛型方法
void GenericFunc<T>(T prop1,T prop2)
{
Debug.Log(typeof(T).FullName);
}

//调用泛型方法
GenericFunc<int>(1, 2);

泛型方法

泛型方法是指通过泛型来约束方法中的参数类型,如果没有泛型,每次方法中的参数类型都是固定的,不能随意更改,在使用泛型后,可以根据提供的泛型来传递不同类型的参数。

  • 参数类型 和 返回类型都可以使用泛型
1
2
3
4
5
//泛型方法
void GenericFunc<T>(T prop1,T prop2)
{
Debug.Log(typeof(T).FullName);
}

泛型类

泛型类是指这个类的某些字段的类型是不确定的,只有在构造的时候才能确定下的类,泛型类一般在数据结构中用的比较多,比如 C# 自带的 List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//泛型类,泛型可以应用于整个类的字段和方法
class MyGenericClass<T>
{
public T firstElementInList;
public List<T> myList;

public bool Append(T element)
{
if(element != null)
{
myList.Add(element);
return true;
}
else
{
return false;
}
}
}

//实例化泛型类
MyGenericClass<int> myGenericClass = new MyGenericClass<int>();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//泛型类的继承
class MyExtendClass<T>:MyGenericClass<T>
{

}

//指定基类的泛型类型
class MyExtendClass:MyGenericClass<float>
{

}

class MyExtendClass<T>:MyGenericClass<float>
{

}

泛型接口

1
2
3
4
5
public interface MyGenericInterface<T>
{
public T getT();

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//普通类实现泛型接口
class MyExtendClass : MyGenericInterface<float>
{
public float getT()
{
return 1.2f;
}
}

//泛型类实现泛型接口
class MyExtendClass<T> : MyGenericInterface<T>
{
private T prop;

public T getT()
{
return prop;
}
}

泛型委托

和普通委托差别不大,只是参数由具体类型变成了T

1
2
3
4
5
6
7
8
delegate void MyDelegate<T>(T arg);

void Func(string argString)
{
Debug.Log(argString);
}

MyDelegate<string> myDelegate = Func;

泛型约束

泛型约束是对 “T” 类型的数据做一定的限制

约束 作用
T :struct 值约束,必须是值类型
T : class 引用约束,必须是引用类型,包括任何类、接口、委托、数组
T : new() 构造函数约束,类型参数必须由无参公共构造函数,和其他约束一起使用时,该约束必须最后指定
T : <基类名> 类型参数必须是指定的基类或派生自指定的基类
T : <接口名称> 类型参数必须是指定的接口或实现指定的接口
T : U 为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//值约束
class MyGenericClass<T>
where T : struct
{
public T firstElementInList;
public List<T> myList;

public bool Append(T element)
{
myList.Add(element);
return true;
}
}

//T : U
class MyGenericClass<T,U>
where T : U
{
public T firstElementInList;
public List<T> myList;

public bool Append(T element)
{
myList.Add(element);
return true;
}
}