using System;
using System.Text;
namespace LyTest
{
class Animal { }
class Bear : Animal { }
class Camel : Animal { }
public class Stack<T> : IPoppable<T>, IPushable<T>
{
int position;
T[] data = new T[100];
//接口实现
public void Push(T obj) => data[position++] = obj;
//接口实现
public T Pop() => data[--position];
}
/*声明接口 声明协变参数T
* out修饰符表明了T只用于 输出位置 例如 方法的返回值
* out修饰符将类型参数T标记为 协变参数
*/
public interface IPoppable<out T> { T Pop(); }
/*声明接口 声明逆变参数T
* in修饰符表明了T只用于 输入位置 例如 方法的参数 or 可写属性
* in修饰符将类型参数T标记为 逆变参数
*/
public interface IPushable<in T> { void Push(T obj); }
class Program
{
public static void Main()
{
Stack<Bear> bears1 = new Stack<Bear>();
bears1.Push(new Bear());
IPoppable<Animal> animals1 = bears1;//协变 子类→基类
//告诉编译器 转换是安全的
// IPoppable<Bear> 可以转换成 IPoppable<Animal>
animals1.Pop();
IPushable<Animal> animals2 = new Stack<Animal>();
IPushable<Bear> bears2 = animals2;//逆变 父类→子类
//告诉编译器 转换是安全的
//IPushable<Animal> 可以转换成 IPushable<Bear>
bears2.Push(new Bear());
}
}
}