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 Stacks<Bear, Animal>();
//IStacks2<Bear, Animal> zoo = bear;
}
}
/*协变:参数传进的是子类,方法返回的是父类,表示父类一定拥有子类的属性,最终一定可以转换*/
/*逆变:参数外部传进的是父类,方法体内用的是子类,表示方法体的子类继承自参数的父类。*/
public interface IStacks<out T1>
{
T1 Pop();
}
public interface IStacks2<in T1, out T2> where T1 : 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;
}
}
}