using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 专高四 { class 协变 { static void Main_协变() { Stacks<Bear> bears = new Stacks<Bear>(); bears.Push(new Bear()); Stacks<Camal> camals = new Stacks<Camal>(); camals.Push(new Camal()); IStacks<Animal> Animal = Bears; Animal = camals; // Stacks <Bear, Animal> Bear = new new Stacks <Bear, Animal> (); // IStacks2 <Bear, Animal> Zoo = Bear; } } / * covariant: parameters are passed into the subclass is the parent class method returns, the parent class must have attributes expressed subclass must eventually be converted * / / * inverter: external parameters passed in is the parent class, method is to use in vivo subclass, a subclass inherits methods body parameters from the parent class. * / Public interface IStacks < OUT Tl> { Tl Pop (); } public interface IStacks2 < in Tl, OUT T2> WHERE Tl: class { T2 Pop(); void Push(T1 obj); } public class Stacks<T1> : IStacks<T1> { T1[] list = new T1[100]; int index; public T1 Pop() { return list[--index]; } public void Push(T1 obj) { list[index++] = obj; } } public class Stacks<T1, T2> : IStacks2<T1, T2> where T1 : class where T2 : class { T2[] list = new T2[100]; int index; public T2 Pop() { return list[--index]; } public void Push(T1 obj) { list[++index] = obj as T2; } } class Animal { } class Bear : Animal { } class Camal : Animal { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 专高四 { class 泛型 { static void Main() { Stacks<string> s = new Stacks<string>(); s.Push("a"); s.Push("b"); s.Push("c"); Console.WriteLine("{0,-11}{1,-11}{2,-11}", s.Pop(), s.Pop(), s.Pop()); ObjHelper<Student> obj = new ObjHelper<Student>(); Student stu1 = new Student { Id = 1, Name = "xiao" }; var stu2 = obj.Clone(stu1); Console.WriteLine(stu2.Id); } } public class ObjHelper<T> where T : new() { public T Clone(T obj) { T t = new T(); t = obj; return t; } } }