C# -- 泛型的使用
1. 使用泛型
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int number = 100; 6 string str = "Hello"; 7 8 //使用泛型方式1,传入参数类型和参数 9 MyTest<int>(number); 10 MyTest<string>(str); 11 12 13 //使用泛型方式2,传入参数-->编译器会根据参数推断出参数的类型 14 MyTest(number); 15 MyTest(str); 16 17 Console.ReadKey(); 18 } 19 20 public static void MyTest<T>(T t) 21 { 22 Console.WriteLine("{0} 的类型是{1}",t.ToString(),t.GetType()); 23 } 24 }
运行结果:
2. 泛型约束
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int number = 20181223; 6 string str = "Hello,2018-12-23"; 7 8 //MyTest1传入参数类型必须是引用类型,否则会编译时报错 9 MyTest1<string>(str); 10 11 //MyTest2传入参数类型必须是值类型,否则会编译时报错 12 MyTest2<int>(number); 13 14 Console.ReadKey(); 15 } 16 17 //限定传入的参数类型是引用类型 18 public static void MyTest1<T>(T t) where T:class 19 { 20 Console.WriteLine("{0} 的类型是{1}",t.ToString(),t.GetType()); 21 } 22 23 //限定传入的参数类型是值类型 24 public static void MyTest2<T>(T t) where T:struct 25 { 26 Console.WriteLine("{0} 的类型是{1}", t.ToString(), t.GetType()); 27 } 28 }
运行结果: