网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

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#协变与抗变详解
网页URL:http://bjjierui.cn/article/gsidpp.html

其他资讯