C#中的泛型

发布时间:2026/7/22 19:12:10
C#中的泛型 泛型是一种对变量类型的参数化在定义类接口或方法时在名称后用一个泛型占位符来代替想要被指定的变量类型在实际用到的时候就可以自主的来指定该变量类型。泛型类泛型接口与泛型函数中的泛型占位符可以不限定于单个即允许有多个泛型占位符。对于继承了了泛型接口的类需要对于指明泛型接口中写的泛型的变量类型。泛型方法中的泛型可以作为参数传入可以作为内部逻辑处理可以作为返回值但要注意对于后两者的处理由于我们在初始声明时无法得知具体的变量类型所以尽量使用变量的默认型default来参与。对于泛型类中的泛型方法内部泛型方法指定的泛型字符不能与外部泛型类指定的泛型字符重复。利用泛型可以处理不同类型对象的相同逻辑处理也可以在一定程度上优化装箱拆箱的内存占用。using System; namespace lesson05 { //泛型类 class TestClassT,K { public T value; public K key; } //泛型接口 interface TestInterFaceM, LL { M Value { get; set; } LL Key { get; set; } } //普通类继承泛型接口时要指定泛型的变量类型 class Test : TestInterFacestring, float { public string Value { get; set; } public float Key { get; set; } } //普通类中的泛型方法 class Test2 { //泛型作为参数传递 public void TestFunT, K(T val, K ke) { Console.WriteLine(第一个泛型参数 val 第二个泛型参数 ke); } //泛型作为内部逻辑处理 public void TestFunT() { T t default;//不论泛型后续被指定为什么变量类型均为默认类型 Console.WriteLine(t); } //泛型作为返回值(确保默认) public T TestFunT(string s) { return default(T); } } //泛型类中的泛型方法 class Test2T { public T value; //泛型类中的泛型方法与泛型类指定的占位符不能相同 public void TestFunK(K k) { Console.WriteLine(${k}); } } //利用泛型优化数组指定所装元素的具体类型避免了装箱拆箱 class ArrayListT { private T[] array; public void Add(T value) {} public void Remove(T value) {} } class Program { static void Main(string[] args) { //实例化泛型类的对象时要指定泛型的变量类型 TestClassint,string t new TestClassint, string(); t.value 10; t.key eee; Console.WriteLine(t.value); Console.WriteLine(***************************); TestClassString,bool t2 new TestClassString, bool(); t2.value abc; t2.key true; Console.WriteLine(t2.value); Test2 tt new Test2(); Console.WriteLine(***************************); //调用普通类中的泛型方法时要指定泛型的变量类型 tt.TestFunstring, float(abcdefg, 3.1f); tt.TestFunbool(); Console.WriteLine(***************************); Test2int tt2 new Test2int(); tt2.TestFunfloat(6.5f); /*当泛型类的泛型与其内部泛型方法的泛型指定了相同的变量类型时 优先调用泛型方法指定的变量类型 */ tt2.TestFunint(3); /* 泛型类内以泛型作为参数的泛型方法的调用时 允许不写出泛型类型而根据括号内的参数类型自动判断 */ tt2.TestFun(yuio); tt2.TestFun(4); } } }