溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C# 協(xié)變與抗變?cè)斀?/h1>
發(fā)布時(shí)間:2020-08-06 06:47:13 來源:網(wǎng)絡(luò) 閱讀:1648 作者:1473348968 欄目:編程語言

-------------------------------------------------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<out T>//協(xié)變
    {
        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<in T>//抗變
    {
        void Kb(T t);//T 只能作為參數(shù)
    }
}

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    public class ListOutIn<T> : IOut<T>, IIn<T>
    {
        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 --> 協(xié)變--> 輸出--> 隱式轉(zhuǎn)換
            //in  --> 抗變--> 輸入--> 顯示轉(zhuǎn)換

            //協(xié)變
            IOut<Animal> oa = new ListOutIn<Animal>();
            IOut<Dog> od = new ListOutIn<Dog>();
            oa = od;//因?yàn)榻涌谑菂f(xié)變的,隱式轉(zhuǎn)換成功
            //抗變
            IIn<Animal> ia = new ListOutIn<Animal>();
            IIn<Dog> id = new ListOutIn<Dog>();
            id = ia;//因?yàn)榻涌谑强棺兊?,顯示轉(zhuǎn)換成功
        }
    }
}

 

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI