范型
字典Dict
//使string键不区分大小写 Dictionary<string, int> things =new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase); Dictionary<string, int> sta = new Dictionary<string, int>() {//初始化索引器 [key] = value ["str1"] = 6, ["str2"] = 7 };
定义范型类
class MyClass<T1,T2,T3> {//不能直接将T1当做类创建实例 private T1 type1; public MyClass(T1 item1) => type1 = item1; public T1 Type1 { get => type1;} public bool Compare(T1 op1,T2 op2) { return op1 != null && op2 != null; } }
Default关键字
用于实例化时为不同类型的字段或属性赋值
class Default关键字<T> { private T t1; /// <summary> /// 当不能确定值类型或引用类型时,用下述方法 /// 此时若T为引用类型则赋值null,T为值类型则赋值0 /// </summary> public Default关键字() { t1 = default(T); } }
约束类型
对范型类型进行约束,使其可用类型受到限制
| 约束 | 定义 |
| struct | 类型必须是值类型 |
| class | 类型必须是引用类型 |
| base-class | 类型必须是基类或继承自基类。可以给这个约束提供任意类名。 |
| interface | 类型必须是接口或实现了接口 |
| new() | 类型必须有一个公共的无参构造函数 |
注意:如果new()用作约束,他就必须是为类型指定的最后一个约束
class Where约束<T1, T2,T3>where T1 :struct where T2 :T3 { //约束必须是接口、非密封类或类型参数 //在继承含有约束的范型时,T不能超集 }
class Animals<T1> where T1:Animal { private List<T1> animal; public List<T1> Animal { get => animal; } public void Tests() { foreach (T1 str in Animal) { //对str操作 } } }
多态性的运用
范型方法与多态性的结合,例如如下方法,可以筛选出任意Animal下的子类型
class Animals<T1> where T1:Animal { private List<T1> animal; public List<T1> Animal { get => animal; } public Animals<U> GetAnimals<U>() where U:T1 {// Animals<U> animalss = new Animals<U>(); foreach (T1 ani in Animal) { if(ani is U) animalss.animal.Add(ani as U);//此处ani必须有明确的类型约束,不然会报错 } return animalss; } }
范型结构
public struct MyStruct<T1,T2> {//范型结构 public T1 t1; public T2 t2; public T1 t3; public T2 t4; }
范型接口
public interface MyAnimalInterface<T1> where T1 : struct {//范型接口 void Test1(T1 a1, T1 a2); int GetInt(T1 a1); T1 GetT1 { get;} }

浙公网安备 33010602011771号