C#菜鸟学习笔记 协变和逆变

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using System.Threading;
using System.Threading.Tasks;

class father
{
    private string lastname;
    public string Lastname { 
        get{return lastname;} 
        set{lastname = value;}
    }
    public father(string lastname)
    {
        Lastname = lastname;
    }
}
class son : father
{
    private string firstname;
    public string Firstname {
        get { return firstname; }
        set { firstname = value; }
    }
    public son(string firstname, string lastname) : base(lastname)
    {
        Firstname = firstname;
    }
}

interface InChange<in T>
{
    void show(T temp);
}
interface OutChange<out T>
{
    T show();
}
interface noT<T>
{

}
class noTF : noT<father>
{

}
class noTS : noT<son>
{

}
class inchange : InChange<father>
{
    public void show(father temp)
    {
        Console.WriteLine("lastname =" + temp.Lastname);
    }
}
class outchange : OutChange<son>
{
    public son show()
    {
        return new son("gang", "wang");
    }
}
class Program
{

    static void Main(string[] args)
    {

        father fa = new father("hao");
        son son = new son("gang","wang");
        Console.WriteLine(fa.Lastname);
        Console.WriteLine(son.Lastname);
        //由于协变,我们可以用父类接口来装子类的接口\
        //out修饰的符号中,泛型T只能是用于返回
        OutChange<son> outson = new outchange();
        OutChange<father> outfather = outson;
        //所以这里,我们可以用fa来接受返回值,只得到fa所需要的部分
        fa = outfather.show();
        Console.WriteLine(fa.Lastname);
        
        //由于逆变,我们可以用子类接口来装父类的接口
        //in修饰的符号中,泛型T只能用于输入
        InChange<father> infather = new inchange();
        InChange<son> inSon = infather;
        //这里,我们可以用father来装这个son,但是这个装的部分是在函数内部
        inSon.show(son);


        //所以,其实无论是协变逆变,都符合里氏替换原则
        //即用父类装子类
        //在协变out中,T用作返回值,所以可以用父接口来等于子接口
        //在逆变in中,T用作参数,所以可以用子接口来等于父接口
        //而没有修饰符的时候,接口不能相互等于、
        noT<father> notF = new noTF();
        noT<son> notS = new noTS();
        //以下的2句代码,会产生报错,因为没有遵循协变和逆变!
        notF = notS;
        notS = notF;
        Console.ReadLine();
    }

   
}

     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值