今天被out參數玩了一把

來源:互聯網
上載者:User

我們經常寫這樣的代碼:

public class Class2
    {
        private void InvokeTest()
        {
            Derive d = new Derive();
            Test(d);
        }
        private void Test(Base b)
        {
        }
    }
    class Base
    {
    }
    class Derive : Base
    {
    }
    class Derive1 : Base
    {
    }

使用基類來表示一個介面,然後傳遞子類。但是把這段代碼改一改:

public class Class2
    {
        private void InvokeTest()
        {
            Derive d = new Derive();
            Test( out d);
        }
        private void Test( out Base b)
        {
            b = ......
        }
    }
    class Base
    {
    }
    class Derive : Base
    {
    }
    class Derive1 : Base
    {
    }

按照平常的思路是沒問題的,可是連編譯都通不過。Why? 是繼承體系不對?查一查,沒問題。參數類型不對?也沒問題,如果把Derive d = new Derive()換成Base d = new Base(),編譯是沒問題的。或者不使用out,編譯也沒問題。
費了老大勁,才找到關於這個問題的說明:
out要求傳入的參數類型和聲明的類型是一致的。原來的是out搞的鬼!對out參數子類到基類的轉換是用不成的,
可是如果new的是基類,那麼使用基類不就沒意義了嗎?
沒辦法,架構是人家寫的,人家用了out參數我們也不能怎麼樣,不過這個問題得搞清楚。要傳子類,還得自己想辦法,繞個道:    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            BaseClass y ;
            Test( out y ,typeof(DeriveClass2) );
            y.WriteName();
            Console.ReadLine();
        }
        static void Test(  out BaseClass y ,Type t )
        {
            y = BaseClass.CreateInstance(t);
        }
    }
    class BaseClass
    {
        public static BaseClass CreateInstance(Type deriveClassType)
        {
            return (BaseClass)System.Activator.CreateInstance(deriveClassType);
        }
        public void WriteName()
        {
            Console.WriteLine(this.ToString());
        }
    }
    class DeriveClass : BaseClass
    {
    }
    class DeriveClass2 : BaseClass
    {
    }

要不是這次碰到這樣的問題,我還真不知道out參數還有這問題呢?照著平常的思路老是走不通,還道是繼承的有問題呢,還好,總算把原因搞清楚了

聯繫我們

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