c#4.0泛型介面和泛型委派的協變和逆變

來源:互聯網
上載者:User

先看個例子,此代碼在c# 4.0下可以編譯通過,因為c#4.0才開始支援逆變和協變

 

代碼

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

namespace ConsoleApplication1
{
 
    class Program
    {
        public static void Main()
        {
            IEnumerable<object> objs = new List<string>(); //協變

            Action<object> action1 = o => { };

            Action<string> action2 = action1;//逆變
        }
    }
}

 

下面是泛型介面IEnumerable<T>相互關聯類型的定義

   

代碼

 public interface IEnumerable<out T> : IEnumerable
    {
        // Summary:
        //     Returns an enumerator that iterates through the collection.
        //
        // Returns:
        //     A System.Collections.Generic.IEnumerator<T> that can be used to iterate through
        //     the collection.
        IEnumerator<T> GetEnumerator();
    }

    public interface IEnumerator<out T> : IDisposable, IEnumerator
    {
        // Summary:
        //     Gets the element in the collection at the current position of the enumerator.
        //
        // Returns:
        //     The element in the collection at the current position of the enumerator.
        T Current { get; }
    }

 

 

可以看到T在IEnumerable定義中比以前多了out的修飾符。out表示T在泛型型別中只能被用作輸出。也就是說T定義的對象是只會被用作賦值給客戶代碼中的引用。這樣凡是使用IEnumerable<BaseType>類型的地方都可以被安全的替換成IEnumerable<SubType>.因為子類型(SubType)可以安全替換父類型(BaseType)

下面是泛型委派Action<T>的定義

 

   public delegate void Action<in T>(T obj);

這裡是用in修飾T。說明T在泛型中只會被用作輸入,也就是說T定義的引用只能用作接受客戶代碼的賦值。所以使用Action<SubType>的地方都可以被安全的替換成Acton<BaseType>.道理和上面一樣子類型(SubType)可以安全替換父類型(BaseType)。

 

總結:協變和逆變允許我們定義的泛型介面和泛型委派能更加的通用。而且保證不會破壞型別安全。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.