Covariant in C#

來源:互聯網
上載者:User
covariant可以理解為變異.也就是一種類型轉換成另一種類型.
Anders在<<The C# Promgramiming Language>>的數組一章中提到了數組的變異.
如果一個參考型別A可以隱式或者顯式地轉化為B,則A[R]也可以轉化成B[R],R可以任意指定,但A,B必須相同,這種關係稱為數組變異.數組變異不能推廣到實值型別,比如不能從int[]轉化成object[],也不能從byte[]轉化成int[].
今天在Bill Wanger的blog上發現了一篇文章,說的是函數傳回型別的變異,C#不支援函數傳回型別的變異,比如下面的代碼是不能通過變異的class ClassParent
    {
        static void Main()
        {

        }
        protected virtual ClassParent GetThing()
        {
            return null;
        }
                
    }

    class ClassSon:ClassParent
    {
        protected override ClassSon GetThing()
        {
            return null;
        }
    }

編譯時間會報錯,當方法重載是不能改變傳回型別,這在C++中是支援的.
Bill Wanger說可以用一個範型介面來實現, 俺的C#是1.1的不支援範型,不過也把代碼粘在下面public interface Producer<T>
    {
        T getThing();
    }

    public class D : Producer <D>
    {
        public D getThing()
        {
            return null;
        }
    }

這樣如果適當限制T的取值,可以利用範型實現C++的函數傳回型別的變異.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.