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; } }
class MyGenericClass<T,U> where T : U { public T firstElementInList; public List<T> myList;
public bool Append(T element) { myList.Add(element); return true; } }
|