C#协变与抗变详解-古蔺大橙子建站
RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
C#协变与抗变详解

-------------------------------------------------Animal.cs

成都创新互联是一家专业从事成都网站设计、网站制作、外贸营销网站建设的网络公司。作为专业网站设计公司,成都创新互联依托的技术实力、以及多年的网站运营经验,为您提供专业的成都网站建设、成都全网营销及网站设计开发服务!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    public class Animal
    {
    }
}

-------------------------------------------------Dog.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    public class Dog:Animal
    {
    }
}

-------------------------------------------------IOut.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    public interface IOut//协变
    {
        T Xb();//T 只能作为返回值
    }
}

-------------------------------------------------IIn.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    public interface IIn//抗变
    {
        void Kb(T t);//T 只能作为参数
    }
}

-------------------------------------------------ListOutIn.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    public class ListOutIn : IOut, IIn
    {
        public T Xb()
        {
            throw new NotImplementedException();
        }
        public void Kb(T t)
        {
            throw new NotImplementedException();
        }
    }
}

-------------------------------------------------主程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //out --> 协变--> 输出--> 隐式转换
            //in  --> 抗变--> 输入--> 显示转换

            //协变
            IOut oa = new ListOutIn();
            IOut od = new ListOutIn();
            oa = od;//因为接口是协变的,隐式转换成功
            //抗变
            IIn ia = new ListOutIn();
            IIn id = new ListOutIn();
            id = ia;//因为接口是抗变的,显示转换成功
        }
    }
}

 


文章题目:C#协变与抗变详解
路径分享:http://scgulin.cn/article/gsidpp.html