2021-7-27 泛型基本练习

using System; using System.Collections.Generic; namespace 泛型的基本使用练习 { class Program { static void Main(string[] args) { //泛型练习1 var a = "aa";var b = "bb"; GetSwap(ref a, ref b); Console.WriteLine(a); Console.WriteLine(b); var aa = 2; var bb =3; GetSwap(ref aa, ref bb); Console.WriteLine(aa.ToString()); Console.WriteLine(bb.ToString()); //泛型练习2 newGeneric<string> program = new newGeneric<string>(5); for (int i = 0; i < 5; i++) { program.SetItem(i, "ss" + i); } for (int i = 0; i < 5; i++) { Console.WriteLine(program.GetItem(i)); } Console.ReadKey(); } public static void GetSwap<T>(ref T first,ref T second)//方法中使用泛型要加在方法名后面 { var a = first; first = second; second = a; } } class newGeneric<S>//此处注意要添加泛型<S>才可以使用 { S[] array; public newGeneric(int index) { array = new S[index + 1];//在构造函数中定义泛型数组的长度 } public S GetItem(int a)//这里的S是返回值 { return array[a]; } public void SetItem(int a, S value) { array[a] = value; } } }
代码奉上