泛型方法 泛型类 泛型接口
//1泛型方法:只需要在方法名字后面加<T,T1,T2> 为了确定参数类型和返回值类型,当然也可以参数和返回值类型定义成普通类型
//2 泛型类:在类名后面添加<T>,目的把类型传入类当中
//3 泛型接口:在接口后面添加泛型,目的把类型传接口当中
实例:
internal class Program { static void Main(string[] args) { People<int,float> p1 = new People<int,float>(); //传入的int 和float类型 p1.F1<float>(10.1f, 10, 20.2f); People<string,string> p2 = new People<string,string>(); p2.F1<string>("昨天黑客攻击", "对国内政府挑衅", "红客联盟白宫服务网站挂上中国国旗"); Student s1 = new Student(); s1.Age = 10; s1.Name = 19.1f; s1.F1<int>(10, 20); Console.ReadKey(); } } //泛型字母可以写任意的字母 class People<TTest1,TTest2> { public string Name { get; set; } public TTest1 A1 { get; set; }// 属性的类型和传入TTest1类型保持一致 public TTest2 A2 { get; set; } // 属性的类型和传入TTest2类型保持一致 public void F1<T>(T c ,TTest1 a,TTest2 b) { dynamic sum = (dynamic)c + (dynamic)a + (dynamic)b; Console.WriteLine(sum); } } //泛型接口 interface IPeople<T> { int Age { get; set; } T Name { get; set; } void F1<T1>(T a,T1 b); } class Student : IPeople<float> { public int Age { get; set; } public float Name { get; set; } public void F1<T1>(float a, T1 b) { Console.WriteLine(a + b.ToString()); } }泛型约束
//4 泛型约束: 泛型本身没有限制类型但是通过 where对泛型进行限制范围
实例
internal class Program { static void Main(string[] args) { //调用Test1方法 Test1<int>(10); Test1("hello"); Test1(DateTime.Now); //调用Test2方法 Test2(10, 10); //Test2<DateTime,int>(DateTime.Now, 10);报错 //Test2("11", 10);报错 //调用Test3方法 Test3("11", "11"); // Test4方法 Test4(new People(),new People()); // Test5方法 Test5(new Student(), new SmallStudent()); //Test6方法 Test6(new People(), new People()); Test6(new SmallStudent(), new Student()); // Test6( new Student(), new SmallStudent()); 报错 Console.ReadKey(); } //本身泛型没有类型限制的 static void Test1<T>(T a) { } // where T : struct 限制T只能值类型 static void Test2<T>(T a,T b) where T : struct { } //where T : class 限制T只能是引用类型 static void Test3<T>(T a, T b) where T : class { } //where T : new() T必须有一个不带参数的构造函数的类 static void Test4<T>(T a, T b) where T : new() { } //where T : IPeople T必须是实现接口的类型 或者实现接口类的派生类, 本例可以是Student、还可以继承于Student的子类:SmallStudent static void Test5<T>(T a, T b) where T : IPeople { } // where T : U 限制传入类型 要么是T和U同一个类型、要么T是U的子类 static void Test6<T,U>(T a, U b) where T : U { } } interface IPeople { } //接口 class Student:IPeople { } // Student实现接口 class SmallStudent:Student { } // SmallStudent继承了 Student //定义people类 class People { public People() { } // 无参数构造 public People(int a) { }// 有参数的构造 }