1. 使用泛型
- class Program
- {
- static void Main(string[] args)
- {
- int number = 100;
- string str = "Hello";
-
- //使用泛型方式1,传入参数类型和参数
- MyTest<int>(number);
- MyTest<string>(str);
- //使用泛型方式2,传入参数-->编译器会根据参数推断出参数的类型
- MyTest(number);
- MyTest(str);
- Console.ReadKey();
- }
- public static void MyTest<T>(T t)
- {
- Console.WriteLine("{0} 的类型是{1}",t.ToString(),t.GetType());
- }
- }
2. 泛型约束
- class Program
- {
- static void Main(string[] args)
- {
- int number = 20181223;
- string str = "Hello,2018-12-23";
- //MyTest1传入参数类型必须是引用类型,否则会编译时报错
- MyTest1<string>(str);
- //MyTest2传入参数类型必须是值类型,否则会编译时报错
- MyTest2<int>(number);
- Console.ReadKey();
- }
- //限定传入的参数类型是引用类型
- public static void MyTest1<T>(T t) where T:class
- {
- Console.WriteLine("{0} 的类型是{1}",t.ToString(),t.GetType());
- }
- //限定传入的参数类型是值类型
- public static void MyTest2<T>(T t) where T:struct
- {
- Console.WriteLine("{0} 的类型是{1}", t.ToString(), t.GetType());
- }
- }