介面、虛方法和抽象方法的CLR處理

來源:互聯網
上載者:User

下面通過一個例子,你可以看到CLR在處理介面、虛方法和抽象方法時的特點。

 public interface ICommon
    {
        void DoIt()
        {
        }
    }

    public class Base :ICommon
    {
        void ICommon.DoIt() { a(); }
        public virtual void DoIt() { b(); }
    }
    public class Derived :Base, ICommon
    {
        void ICommon.DoIt() { c(); }
        public new virtual void DoIt() { d(); }
    }
    public class ReallyDerived : Derived
    {
        public override void DoIt() { e(); }
    }

 

 static void Main(string[] args)
        {

            ReallyDerived r1 = new ReallyDerived();
            Derived r2 = r1;
            Base r3 = r1;
            ICommon r4 = r1;

            r1.DoIt();
            r2.DoIt();
            r3.DoIt();
            r4.DoIt();

        }

 

第一個方法將調用分發給e,因為對象的具體類型有一個名為DoIt的public方法;

第二個方法將調用分發給e,因為Derived.DoIt被聲明為virtual;

第三個方法將調用分發給b,因為即便是Base.DoIt被聲明為virtual,但後續的派生方法還是重載了它的使用;

第四個方法將調用分發給c,因為ICommon.DoIt隱式地為virtual。

當然,你可能不會這樣寫代碼,不過,這可能(也可能不能)有助於你認識到CLR支援這種方式。

聯繫我們

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